實(shí)現(xiàn)x的n次方計(jì)算,二分
1 #50
2 #Runtime: 14 ms (Beats 83.42%)
3 #Memory: 13.2 MB (Beats 69.77%)
4
5 class Solution(object):
6 def myPow(self, x, n):
7 """
8 :type x: float
9 :type n: int
10 :rtype: float
11 """
12
13 def cal(x, n):
14 if n == 0:
15 return 1.0
16 if n % 2:
17 return cal(x * x, n // 2) * x
18 else:
19 return cal(x * x, n // 2)
20
21 if n < 0:
22 return 1.0 / cal(x, -n)
23 return cal(x, n)