Implement pow(x, n), which calculates x raised to the power n(xn).
Example 1:
Input: 2.00000, 10 Output: 1024.00000
Example 2:
Input: 2.10000, 3 Output: 9.26100
Example 3:
Input: 2.00000, -2 Output: 0.25000 Explanation: 2-2 = 1/22 = 1/4 = 0.25
Note:
- -100.0 < x < 100.0
- n is a 32-bit signed integer, within the range [−231, 231 − 1]
這道題讓我們求x的n次方,如果只是簡單的用個 for 循環讓x乘以自己n次的話,未免也把 LeetCode 上的題想的太簡單了,一句話形容圖樣圖森破啊。OJ 因超時無法通過,所以需要優化,使其在更有效的算出結果來們可以用遞歸來折半計算,每次把n縮小一半,這樣n最終會縮小到0,任何數的0次方都為1,這時候再往回乘,如果此時n是偶數,直接把上次遞歸得到的值算個平方返回即可,如果是奇數,則還需要乘上個x的值。還有一點需要引起注意的是n有可能為負數,對於n是負數的情況,我可以先用其絕對值計算出一個結果再取其倒數即可,之前是可以的,但是現在 test case 中加了個負2的31次方后,這就不行了,因為其絕對值超過了整型最大值,會有溢出錯誤,不過可以用另一種寫法只用一個函數,在每次遞歸中處理n的正負,然后做相應的變換即可,代碼如下:
解法一:
class Solution { public: double myPow(double x, int n) { if (n == 0) return 1; double half = myPow(x, n / 2); if (n % 2 == 0) return half * half; if (n > 0) return half * half * x; return half * half / x; } };
這道題還有迭代的解法,讓i初始化為n,然后看i是否是2的倍數,不是的話就讓 res 乘以x。然后x乘以自己,i每次循環縮小一半,直到為0停止循環。最后看n的正負,如果為負,返回其倒數,參見代碼如下:
解法二:
class Solution { public: double myPow(double x, int n) { double res = 1.0; for (int i = n; i != 0; i /= 2) { if (i % 2 != 0) res *= x; x *= x; } return n < 0 ? 1 / res : res; } };
Github 同步地址:
https://github.com/grandyang/leetcode/issues/50
類似題目:
參考資料:
https://leetcode.com/problems/powx-n/
https://leetcode.com/problems/powx-n/discuss/19733/simple-iterative-lg-n-solution
https://leetcode.com/problems/powx-n/discuss/19546/Short-and-easy-to-understand-solution
https://leetcode.com/problems/powx-n/discuss/19544/5-different-choices-when-talk-with-interviewers