LeetCode 50 Pow(x, n)

有关递归与分治的做题笔记,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

猜你喜欢

转载自blog.csdn.net/fongim/article/details/90137330