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)
时间复杂度:O(log(n))
空间复杂度:O(1)
非递归: iterative
# https://algo.monster/liteproblems/50
follow up
class Solution:
def superPow(self, a: int, b: List[int]) -> int:
mode = 1337
ans = 1
for i in b:
ans = pow(ans, 10, mode) * pow(a, i, mode)
return ans % mode