方法一 递归
public class Solution {
public double Power(double base, int exponent) {
if(base == 0 && exponent != 0) {
return 0.0;
}
if(base != 0 && exponent == 0) {
return 1.0;
}
if(exponent < 0) {
base = 1 / base;
exponent = -exponent;
}
//判断exponent的奇偶性
int k = exponent & 1;
if(k == 0) {
//当exponent为偶数的时候,x^n = x^(n/2) * x^(n/2)
return Power(base, exponent / 2) * Power(base, exponent / 2);
}else {
//当exponent为奇数的时候,x^n = x * x^(n/2) * x^(n/2)
return base * Power(base, exponent / 2) * Power(base, exponent / 2);
}
}
}