[leetcode][50] Pow(x, n)
阿新 • • 發佈:2018-09-19
遍歷 urn int x的n次方 input 分解 output 是我 2.0
50. Pow(x, n)
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次方。沒做出來。。。- -
參考答案(別人寫的)
public class Solution { public double MyPow(double x, int n) { double ans = 1; long absN = Math.Abs((long)n); while(absN > 0) { if((absN&1)==1) ans *= x; absN >>= 1; x *= x; } return n < 0 ? 1/ans : ans; } }
代碼很少,但是我感覺這個方法在很多地方都用到了,他這裏是把一個整數分解成2進制數,比如:
9 = 2^3 + 2^0 = 1001
x^9 = x^(2^3) * x^(2^0)
先判斷abs的二進制數低位有沒有1,有的話就ans乘以x,沒有的話就直接x乘以x,到最後肯定還是x乘以ans,每次循環absN都除2.類似於提取公因數2。比如:
14 = 2^3 + 2^2; 第一次循環: ans = 1; xNew = x^2; absN = 14; 第二次循環: ans = x^2; xNew = x^(2+2); absN = 7; 第三次循環: ans = x^(2+2+2); xNew = x^(2+2+2+2); abs = 3; 第四次循環: anx = x^(2+2+2+2+2+2+2); xNew = x^(2+2+2+2+2+2+2+2); abs=1;
每次循環就是遍歷n的二進制的一位。
[leetcode][50] Pow(x, n)