Pow(x, n)
Implement pow(x, n).
思路:直接for循环,效率太低,可以用剑指offer的P93页的方法用递归的方法,或者另一个思路
Consider the binary representation of n. For example, if it is "10001011", then x^n = x^(1+2+8+128) = x^1 * x^2 * x^8 * x^128. Thus, we don't want to loop n times to calculate x^n. To speed up, we loop through each bit, if the i-th bit is 1, then we add x^(1 << i) to the result. Since (1 << i) is a power of 2, x^(1<<(i+1)) = square(x^(1<<i)). The loop executes for a maximum of log(n) times.
该方法通过扫描n的二进制表示形式里不同位置上的1,来计算x的幂次。
剑指offer的思路:
double pow(double x, int n)
{
if(n==0)
return 1.0;
if(n<0)
return 1.0/pow(x,-n);
double half = pow(x,n>>1);
if(n%2==0)
return half*half;
else
return half*half*x;
}
但是leetcode貌似一用递归就报溢出。。。
新思想的;
public class Solution {
public double myPow(double x, int n)
if(n==0) return 1;
else if(n<0) {
x = 1/x;
n = -1 * n;
}
double result = 1;
while(n>0) {
if(n %2 ==1)
result *= x;
n = n >> 1;
x *= x;
}
return result;
}
}