public class Solution {
public double Power(double base, int exponent) {
boolean inCheck = true;
double result = 0.0;
if(equal(base,0.0)&& exponent< 0){
inCheck = false;
return 0.0;
}
if(!equal(base,0.0)&& exponent == 0)
return 1.0;
if(exponent > 0){
result= absPower(base,exponent);
}else{
result= absPower(base,-exponent);
result= 1/result;
}
return result;
}
public double absPower(double base,int exponent){
double tem = 1.0;
for( int i= 0;i< exponent;i++){
tem = base*tem;
}
return tem;
}
boolean equal (double nun1,double nun2){
if((nun1-nun2> -0.0000001)&&(nun1-nun2)<0.0000001)
return true;
else
return false;
}
}
递归求解正数的次方方法
public double absPower(double base,int exponent){
if(exponent == 0)
return 1;
if(exponent == 1)
return base;
double tem = absPower(base,exponent>>1);
tem *=tem;
if(exponent % 2==1)
tem *= base;
return tem;
}
== 注意==
java与c和C++不同的地方,java有boolean类型的数据,不用1和0代表true和false。所以不能用位运算代替求余操作。
递归: