問題描述
實現 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
解題報告
核心就是減少重複計算。例如 ,如果通過 ,那麼就可以直接將這個結果進行平方即可,而不需要重新執行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