给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。
自己写的垃圾代码
class Solution {
public:
double Power(double base, int exponent) {
double re = 1;
if(exponent == 0){
return 1;
}
else if(exponent <= 0){
for(int i=0;i<-exponent;i++){
re*=base;
}
return 1/re;
}else{
for(int i=0;i<exponent;i++){
re*=base;
}
return re;
}
}
};
大牛代码
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;
}
};