美文网首页
LeetCode 50 Pow(x, n)

LeetCode 50 Pow(x, n)

作者: 划水型派大星 | 来源:发表于2019-05-12 09:48 被阅读0次

有关递归与分治的做题笔记,Python实现

50. Pow(x, n)

LeetCodeCN 第50题链接

第一种方法:递归

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:
            return x * self.myPow(x, n - 1)
        return self.myPow(x * x, n / 2)

第二种方法:循环

class Solution:
    def myPow(self, x: float, n: int) -> float:
        if n < 0:
            x = 1 / x
            n = -n
        ans = 1
        while n:
            # n&1 是与运算,用来求奇偶,效果与 n%2 一样
            if n & 1:
                ans *= x
            x = x * x
            # n>>=1 是位运算,右移一位,效果与 n//=2 一样
            n >>= 1
        return ans

下一题:169. 求众数 Majority Element

相关文章

网友评论

      本文标题:LeetCode 50 Pow(x, n)

      本文链接:https://www.haomeiwen.com/subject/mrgqaqtx.html