1 """
2 Implement pow(x, n), which calculates x raised to the power n (xn).
3 Example 1:
4 Input: 2.00000, 10
5 Output: 1024.00000
6 Example 2:
7 Input: 2.10000, 3
8 Output: 9.26100
9 Example 3:
10 Input: 2.00000, -2
11 Output: 0.25000
12 Explanation: 2-2 = 1/22 = 1/4 = 0.25
13 """
14 class Solution:
15 def myPow(self, x, n):
16 if n < 0:
17 x = 1 / x # 巧妙的转换了n<0的情况
18 n = -n
19 res = 1.0
20 while n:
21 if n % 2 != 0: # n & 1 与运算高级写法,快了一点
22 res *= x
23 x *= x
24 n = n // 2 # n >>= 1
25 return res