数值的整数次方
给定一个double类型的浮点数base和int类型的整数exponent,求base的exponent次方
保证base和exponent不同时为0.
题解:
主要是是有三种方法。
1)暴力法:
class Solution {
public:
double Power(double base, int exponent) {
long double res;
if(base==0)
return 0;
if(exponent==0)
return 1;
if(exponent==1)
return base;
int ex=abs(exponent);
res=base;
for(int i=1;i<ex;i++){
res=base*res;
}
return exponent>0?res:1/res;
}
};
2)内置函数法
class Solution {
public:
double Power(double base, int exponent) {
return pow(base,exponent);
}
};
3)快速幂
例如:
36=3(110)=34+2=34*32=34*32*30
class Solution {
public:
double Power(double base, int exponent) {
if (exponent < 0) {
base = 1 / base;
exponent = abs(exponent);
}
long double res= 1.0;
while (exponent) {
if (exponent&1) {
res=res* base;
}
base =base*base;
exponent >>= 1;
}
return ret;
}
};