Skip to main content

16 数值的整数次方

牛客

当 n 为偶数时,a^n = a^(n/2) a^(n/2), n 为奇数时 a^n = a((n-1)/2) a((n-1)/2) * a

时间复杂度 log(n)

public class Solution {
public double Power(double base, int exponent) {
if(exponent==0) return 1;

if(exponent<0) return 1.0/powerCore(base, -exponent);
return powerCore(base, exponent);
}

private double powerCore(double base, int exponent){

if(exponent==1) return base;
if((exponent & 0x1) ==1){
return Power(base,(exponent-1)>>1) * Power(base,(exponent-1)>>1) * base;
} else {
return Power(base, exponent>>1) * Power(base, exponent>>1);
}
}
}