题目链接:数值的整数次方
思路:二分法。对幂次方进行二分,但需要考虑次方运算的特殊情况,这儿,0次方结果都为0,底数为1时结果都为1。
代码:
class Solution {
public double myPow(double x, int n) {
if(x == 1 || x == 0) return x;
if(n == 0) return 1;
return helper(n < 0 ? 1 / x : x, n < 0 ? -1 * (long)n : (long)n);
}
private double helper(double x, long exp){
if(exp == 1) return x;
double t = helper(x, exp>>1);
return (exp & 1) == 1 ? t * t * x : t * t;
}
}