给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。
public class Power {
//输入错误标志
boolean inValidInput=false;
public double Power(double base, int exponent) {
if(equalDouble(base,0.0)&&exponent<=0){
inValidInput=true;
return 0;
}
int exponent2=Math.abs(exponent);
double res = getRes(base, exponent2);
//这个慢
//double res = getRes2(base, exponent2);
if(exponent<0){
res=1.0/res;
}
return res;
}
/*
* 计算速度会变快
* a^n= a^(n/2)*a^(n/2) //n为偶数
* a^((n-1)/2)*a^((n-1)/2)*a //n为寄数
* */
private double getRes(double base, int exponent) {
if(exponent==0)
return 1;
if(exponent==1)
return base;
double res=getRes(base,exponent>>1);
res*=res;
if((exponent&1)==1){//判断exponent奇偶性
res*=base;
}
return res;
}
//计算速度不快
private double getRes2(double base, int exponent) {
double res=1.0;
for (int i=0;i<exponent;i++){
res*=base;
}
return res;
}
private boolean equalDouble(double d1,double d2){
if(Math.abs(d1-d2)<0.0000001){
return true;
}
return false;
}
}