50. Pow(x, n)
Implement pow(x, n).
leetcode 上的top解法
- nest myPow
double myPow(double x, int n) {
if(n<0) return 1/x * myPow(1/x, -(n+1));
if(n==0) return 1;
if(n==2) return x*x;
if(n%2==0) return myPow( myPow(x, n/2), 2);
else return x*myPow( myPow(x, n/2), 2);
}
- double myPow
double myPow(double x, int n) {
if(n==0) return 1;
double t = myPow(x,n/2);
if(n%2) return n<0 ? 1/x*t*t : x*t*t;
else return t*t;
}
- double x
double myPow(double x, int n) {
if(n==0) return 1;
if(n<0){
n = -n;
x = 1/x;
}
return n%2==0 ? myPow(x*x, n/2) : x*myPow(x*x, n/2);
}
- iterative one
double myPow(double x, int n) {
double ans = 1;
unsigned long long p;
if (n < 0) {
p = -n;
x = 1 / x;
} else {
p = n;
}
while (p) {
if (p & 1)
ans *= x;
x *= x;
p >>= 1;// n>>=1 中的>>=意思是先将变量n的各个二进制位顺序右移1位,最高位补二进制0,然后将这个结果再复制给n。
}
return ans;
}
- bit operation