书中方法:这道题要注意底数为0的情况。double类型的相等判断。乘方的递归算法。
public double power(double base, int exponent){
//指数为0
if(exponent == 0){
return 1.0;
}
//底数为0
if(isEqual(base, 0.0)){
return 0.0;
}
int absExponent = exponent;
if(exponent < 0)absExponent = -absExponent;
double result = unsignedPower(base, absExponent);
if(exponent<0){
result = 1.0/result;
}
return result;
}
//求乘方正常思路
private double unsignedPower(double base, int absExponent){
double result = 1.0;
for(int i=1; i<=absExponent; i++){
result *= base;
}
return result;
}
//用递归的方法求乘方
private double unsignedPower2(double base, int absExponent){
if(absExponent == 1)return base;
double result = unsignedPower2(base, absExponent>>1);
result *= result;
if((absExponent & 0x01) == 1){
result *= base;
}
return result;
}
//double类型判断相等
private boolean isEqual(double num1, double num2){
if((num1 - num2)>-0.0000001 && (num1 - num2)<0.0000001){
return true;
}else{
return false;
}
}