问题描述
实现 pow(x,n),即计算x的n次幂函数。
示例 1:
输入: 2.00000, 10
输出: 1024.00000
示例 2:
输入: 2.00000, -2
输出: 0.25000
解释: 2-2 = 1/22 = 1/4 = 0.25
解题报告
核心就是减少重复计算。例如 4 10 = ( 4 5 ) 2 4^{10}=(4^5)^2 410=(45)2,如果通过 4 5 = 4 ∗ 4 ∗ 4 ∗ 4 ∗ 4 4^5=4*4*4*4*4 45=4∗4∗4∗4∗4,那么就可以直接将这个结果进行平方即可,而不需要重新执行5次算法操作。
实现代码
- 我实现的代码
class Solution {
public:
double myPow(double x, int n) {
int flag=n>0;
if(n==1) return x;
if(n==0) return 1.0;
n=abs(n);
double tmp=myPow(x, n/2);
if(n%2==0)
return flag?tmp*tmp:1/(tmp*tmp);
else
return flag?tmp*tmp*x:1/(tmp*tmp*x);
}
};
- 评论区
Victor
代码
class Solution {
public:
inline double positivePow(double x, long n) {
double res = 1, t = x;
while (n) {
if (n & 1) {
res *= t;
}
t *= t;
n >>= 1;
}
return res;
}
double myPow(double x, long n) {
if (n < 0) {
n = -n;
x = 1.0 / x;
}
return positivePow(x, n);
}
};
参考资料
[1] Leetcode 50. Pow(x, n)
[2] 评论区 Victor