題目鏈接
tag:
- Medium胰默;
question:
??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]
思路:
??考慮邊界條件較多毕谴,然后用到除2的數(shù)學(xué)關(guān)系式即可养葵,我們讓i初始化為n懊蒸,然后看i是否是2的倍數(shù)兴使,是的話x乘以自己,否則res乘以x灾常,i每次循環(huán)縮小一半乞封,直到為0停止循環(huán)。最后看n的正負(fù)岗憋,如果為負(fù)肃晚,返回其倒數(shù),參見(jià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;
}
};