解1 递归
(1)
每次递归进入 对幂-1,但超出时间限制
class Solution:
def myPow(self, x: float, n: int) -> float:
if n == 0:
return 1.0
if n < 0:
x = 1 / x
n = -n
return x * self.myPow(x, n - 1)
(2)
想办法加快幂递减的速度
当幂为偶数时,可对幂减少一半
class Solution:
def myPow(self, x: float, n: int) -> float:
if n == 0:
return 1.0
if n < 0:
x = 1 / x
n = -n
if n % 2:
return x * self.myPow(x, n - 1)
else:
# 加快n递减的速度
return self.myPow(x * x, n / 2)
(3)
每次递归 都对幂进行除以2 取整
- 奇数 return x * myPow(x * x, n // 2)
- 偶数 return myPow(x * x, n // 2)
例如:5 ^ 11 = 5 * 5 ^ 10 = 5 * (5 ^ 2) ^ 5
class Solution:
def myPow(self, x: float, n: int) -> float:
if n == 0:
return 1.0
if n < 0:
x = 1 / x
n = -n
if n % 2:
return x * self.myPow(x * x, n // 2)
else:
return self.myPow(x * x, n // 2)
解2 迭代
class Solution:
def myPow(self, x: float, n: int) -> float:
if n == 0:
return 1.0
if n < 0:
x = 1 / x
n = -n
result = 1
while n:
if n % 2:
result *= x
n //= 2
x *= x
return result