解题思路:
快速幂算法(递归)
class Solution {
public double myPow(double x, int n) {
long N = n;
//需要注意n如果为−2的31次方,转为整数会溢出,因此要用一个long型N
if (N < 0) {
x = 1 / x;
N = -N;
}
return helper(x,N);
}
public double helper(double x,long n){
if(n==0){
return 1.0;
}
double tmp = helper(x, n / 2);
if(n%2==0){
return tmp*tmp;
}
else{
return tmp*tmp*x;
}
}
}
原题地址:
50. Pow(x, n)