实现 pow(x, n) ,即计算 x 的 n 次幂函数(即,xn)。不得使用库函数,同时不需要考虑大数问题。
快速幂
注意考虑n<0的情况
class Solution {
public double myPow(double x, int n) {
double res = 1;
if(n == 0){
return res;
}
if(n > 0){
while(n > 0){
if((n & 1) == 0){
n >>= 1;
x *= x;
}
else{
n = n - 1;
res = res * x;
}
}
}else{
while(n < 0){
if((n & 1) == 0){
n >>= 1;
x *= x;
}
else{
n = n + 1;
res = res / x;
}
}
}
return res;
}
}