代码
分析
数值的整数次方
代码
public class Solution {
public double Power(double base, int exponent) {
if(base==0&&exponent<=0){
return 0;
}
int total=1;
for(int i=0;i<Math.abs(exponent);i++){
total*=base;
}
if(exponent<0){
return 1.0/total;
}
return total;
}
public double Power2(double base, int exponent) {
if(base==0&&exponent<=0){
return 0;
}
double total=PowerCore(base,Math.abs(exponent));
if(exponent<0){
return 1.0/total;
}
return total;
}
public double PowerCore(double base,int exponent){
if(exponent==0){
return 1.0;
}
if(exponent==1){
return base;
}
double result=PowerCore(base,exponent>>1);
result*=result;
if((exponent&1)==1){//此处一定要加括号,==操作符优先级大于&
result*=base;
}
return result;
}
}