快速幂
class Solution:
def myPow(self, x: float, n: int) -> float:
if x == 0:
return 0
# 幂数为负数,取倒数
if n < 0:
x, n = 1/x, -n
result = 1
# 二分法求快速幂
while n:
# 当幂数为奇数的时候,先乘一个将其变为偶数
if n & 1:
result *= x
# 每次幂数除以2(向下取整,前面已经考虑过奇数的问题),数值取平方
x *= x
n >>= 1
# 最左边一位总是1,所以能够乘到result上
return result
更加直观一点还可以使用等价的递归的写法
def myPow(self, x: float, n: int) -> float:
if n == 0:
return 1
if n < 0:
return 1 / self.myPow(x, -n)
# 如果是奇数
if n & 1:
return x * self.myPow(x, n - 1)
return self.myPow(x * x, n // 2)