50. Pow(x, n)
solution
class Solution:
def myPow(self, x: float, n: int) -> float:
if n == 0: # 退出递归的关键返回
return 1
if n < 0:
return 1 / self.myPow(x, -n)
if n % 2 == 1:
return x * self.myPow(x, n - 1)
return self.myPow(x * x, n // 2) # 注意是 (x ** 2 ^ n//2) 而不是 (x ^ n//2 ^ 2)# https://algo.monster/liteproblems/50
follow up
Last updated