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)

方法二:非递归写法(将指数看成二进制数)

16. 数值的整数次方

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/

相关文章:

  • 2022-12-23
  • 2021-08-01
  • 2022-12-23
  • 2022-01-12
猜你喜欢
  • 2022-12-23
  • 2022-02-11
  • 2022-01-23
  • 2022-01-26
  • 2021-05-26
相关资源
相似解决方案