class Solution {
public:
double Power(double base, int exponent) {
double res = 1;
if(exponent == 0)
return 1;
if(exponent > 0)//正常快速幂
{
while(exponent)
{
if(exponent & 1)
res *= base;
exponent >>= 1;
base *= base;
}
return res;
}
else
{
exponent = -exponent;//先把指数变为正
while(exponent)
{
if(exponent & 1)
res *= base;
exponent >>= 1;
base *= base;
}
return 1.0 / (res*1.0);//倒数就是结果
}
}
};
递归版本实现链接:
https://blog.youkuaiyun.com/ustcer_93lk/article/details/80369990