Description
Implement pow(x, n), which calculates x
raised to the power n
(i.e., xn
).
Example 1:
Input: x = 2.00000, n = 10
Output: 1024.00000
Example 2:
Input: x = 2.10000, n = 3
Output: 9.26100
Example 3:
Input: x = 2.00000, n = -2
Output: 0.25000
Explanation: 2-2 = 1/22 = 1/4 = 0.25
Constraints:
-100.0 < x < 100.0
-231 <= n <= 231-1
n
is an integer.
-104 <= xn <= 104
Code
Brute Force (TLE)
O(n) Multiplications
Recursion
是為了避免 x =1.00000, n =-2147483648 這種 case 會導致 integer overflow。
Log
O(log2n) Multiplications
例如 n = 11
,寫成二進位為 1011
,我們就不斷地 right shift,用 if(n & 1)
檢查 right most bit 是否為 1
來決定是否要乘上此時的 x
。
Source