题目描述
给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。
保证base和exponent不同时为0
class Solution {
public:
double Power(double base, int exponent) {
if (exponent==0) return 1;
double ret=pow(Power(base,abs(exponent)/2),2);
if (abs(exponent)%2==1)
ret*=base;
return exponent<0?1/ret:ret;
}
};
public:
double Power(double base, int exponent) {
if (exponent==0) return 1;
double ret=pow(Power(base,abs(exponent)/2),2);
if (abs(exponent)%2==1)
ret*=base;
return exponent<0?1/ret:ret;
}
};
//简单快速幂
class Solution {
public:
double Power(double base, int exponent) {
long long p=abs((long long) exponent);
double r=1.0;
while (p){
if (p&1) r*=base;
base*=base;
p>>=1;
}
return exponent <0 ?1/r :r;
}
};
class Solution {
public:
double Power(double base, int exponent) {
long long p=abs((long long) exponent);
double r=1.0;
while (p){
if (p&1) r*=base;
base*=base;
p>>=1;
}
return exponent <0 ?1/r :r;
}
};