Pow(x, n)


Implement pow(x, n).


Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class {
public double myPow(double x, int n) {
if(n==0) return 1;
if(x==1) return 1;
if(x==-1) return (n%2)==0?1:-1;
if(n == Integer.MIN_VALUE) return 0;
if(n<0) {
n = -n;
x = 1/x;
}
//非递归、位运算
double res = 1;
while(n > 0) {
if((n&1)==1) res *= x;
x *= x;
n >>= 1;
}
return res;
}
}