題解 | #數(shù)值的整數(shù)次方#
數(shù)值的整數(shù)次方
http://www.fangfengwang8.cn/practice/1a834e5e3e1a4b7ba251417554e07c00
需要注意base同時(shí)做平方運(yùn)算,因?yàn)橛乙埔晃皇瞧椒降?/p>
public double Power(double base, int exponent) {
if(base == 0 && exponent == 0){
return 0;
}
if(exponent < 0){
base = 1 / base;
exponent = -exponent;
}
double res = 1.0;
while(exponent > 0){
if((exponent&1) == 1){
res *= base;
}
exponent >>= 1 ;
base *= base ;//base同時(shí)做平方運(yùn)算
}
return res;
}
}