思路:还是利用二分法的思想,从times = 1开始,将其每次扩大两倍,直到times > n,同时x也会每次扩大两倍。将 n减去 times,重复前面的步骤,直到times为0。我这里采用了n分为奇数和偶数的分别处理,复杂化了代码,其实完全没必要这样。
class Solution {
public:
double pow(double x, int n) {
if(0 == n) return 1;
int isNegative = n <0 ? -1:1;
long long N = n, times;
N = abs(N);
long double X = x, ret = 1;
while(N>0){
long double temp = X;
times = 2;
if(N%2 == 1) {
ret *= X;
N -= 1;
}
else{
while(N - times >=0){
temp *= temp;
times <<= 1;
}
ret *= temp;
times >>= 1;
N -= times;
}
}
if(isNegative == -1)ret = 1 / ret;
return ret;
}
};