题目描述
给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。
public class Solution {
public double Power(double base, int exponent) {
if(exponent == 0){
return 1;
}
if(exponent == 1){
return base;
}
double ret = 0;
if(exponent > 0){
//奇数
if(exponent%2!=0){
double tmp = Power(base,exponent/2);
ret = tmp*tmp*base;
}else{//偶数
double tmp = Power(base,exponent/2);
ret = tmp*tmp;
}
}else{
//奇数
exponent = 0 - exponent;
if(exponent%2!=0){
double tmp = Power(base,exponent/2);
ret = 1/(tmp*tmp*base);
}else{//偶数
double tmp = Power(base,exponent/2);
ret = 1/(tmp*tmp);
}
}
return ret;
}
}
2017.5.30第二次做这道题,代码稍微简洁些:
public class Solution {
public double Power(double base, int exponent) {
if(exponent==0){
return 1;
}
if(exponent==1){
return base;
}
if(exponent<0){
return 1/Power(base,exponent*(-1));
}
int a = exponent/2;
int b = exponent%2;
double c = Power(base,a);
if(b==0){
return c*c;
}
return c*c*base;
}
}