Posted on 2023-07-24 19:38
Uriel 閱讀(46)
評論(0) 編輯 收藏 引用 所屬分類:
閑來無事重切Leet Code 、
二分.三分
實現x的n次方計算,二分
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)