16. 数值的整数次方
方法一:递归写法(分治思想)
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 & 1:
return x * self.myPow(x, n - 1)
return self.myPow(x * x, n >> 1)
方法二:非递归写法(将指数看成二进制数)
class Solution:
def myPow(self, x: float, n: int) -> float:
if n < 0:
x = 1 / x
# 负数变成正数
n = -n
res = 1
while n:
if n & 1:
res *= x
x *= x
n >>= 1
return res
链接:https://leetcode-cn.com/problems/shu-zhi-de-zheng-shu-ci-fang-lcof/solution/di-gui-xie-fa-fen-zhi-si-xiang-yu-fei-di-gui-xie-f/