剑指 Offer 16. 数值的整数次方 - 力扣(LeetCode) (leetcode-cn.com)
目录
运行结果
分析
如何快速求出x的高次幂?
注意到,n可以写成以下形式:
n = 2*p + q
其中:
p = n / 2 = n >> 1
q = n % 2 = n & 1
则
pow(x, n) = pow(x*x, p) * pow(x, q)
根据上式进行递归即可。
代码
class Solution {
public:
double myPow(double x, int n) {
int64_t N = n;
return N >= 0 ? power(x, N) : 1 / power(x, -N);
}
double power(double x, int64_t n) {
if (!n) return 1;
return power(x * x, n >> 1) * ((n & 1) ? x : 1);
}
};