-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfindpower_19.java
42 lines (40 loc) · 1.07 KB
/
findpower_19.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// Implement a function to calculate X^N. Both X and N can be positiveor negative.
// You can assume that overflow doesn't happen.
// time - O(log n)
// space - O(1)
public class findpower_19{
public static float power(int x, int n){
if (x == 0 && n <= 0) {
throw new ArithmeticException("undefined");
}
float result = posPower(Math.abs(x), Math.abs(n));
if(n < 0){
result = 1 / result;
}
if(x < 0 && n % 2 != 0){
result = -1 * result;
}
return result;
}
public static int posPower(int x, int n){
if(n == 0){
return 1;
}
if(x == 0){
return 0;
}
int halfPower = posPower(x, n/2);
if(n % 2 == 0){
return halfPower * halfPower;
}
else{
return x * halfPower * halfPower;
}
}
public static void main(String[] args) {
int x = 2;
int power = 0;
float result = power(x, power);
System.out.print(result);
}
}