题目描述
给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。
按通常思路,但时间耗时还是挺多的,毕竟CPU不善于计算乘法,更善于移位操作.
通常思路对应的代码:
class Solution {
public:
double Power(double base, int exponent) {
float sum=1.0f;
float s=0;
if(exponent>=0){
for(int i =0;i<exponent;i++){
sum*=base;
}
s=sum;
}
else{
for(int i =0;i<(-exponent);i++){
sum*=base;
}
s=1.f/sum;
}
return s;
}
};
使用快速幂:
class Solution {
public:
double Power(double base, int exponent) {
long long e = abs(exponent);
float sum=1.0f;
float s=0;
while(e!=0){
if(e & 1) //与 e%2==1功能相同
sum = sum*base; //如果符合条件说明需要将更新后的base连乘
base *=base;
e = e>>1;
} //求出e的反二进制,每次算出反二进制的一个数就参与运算
s = exponent>=0?sum : 1/sum;
return s;
}
};
另外请参考快速幂