力扣刷题笔记:50.Pow(x, n)(二分法、普通和位运算两种写法,方法一样,很好理解)

题目:

50、Pow(x, n)

实现 pow(x, n) ,即计算 x 的 n 次幂函数(即,xn)。

示例 1:
在这里插入图片描述
示例 2:
在这里插入图片描述
示例 3:
在这里插入图片描述
提示:
在这里插入图片描述

题解思路:

二分法,通过折半计算,每次把 n 减半,降低时间复杂度。

两种写法:
一、普通写法。
二、位运算写法。

注:其实都是一样的意思,达到一样的效果。速度也差不多
例如 n>>=1 等价于 n/=2 ; n%2 == 1 等价于 n&1 == 1(判断是否为奇数)

在这里插入图片描述

题解python代码:

一、普通写法

class Solution:
    def myPow(self, x: float, n: int) -> float:
        res = 1
        if n < 0: x,n = 1/x,-n
        while n:  # 通过折半计算,每次把 n 减半,降低时间复杂度
            if n%2 == 0:
                x *= x
                n /= 2
            else:
                res *=x
                n -= 1
        return res

二、位运算写法

class Solution:
    def myPow(self, x: float, n: int) -> float:
        res = 1
        if n < 0: x, n = 1 / x, -n
        while n:
            if n & 1: res *= x
            x *= x
            n >>= 1
        return res

作者:a-qing-ge
链接:https://leetcode-cn.com/problems/powx-n/solution/er-fen-fa-pu-tong-xie-fa-yi-ji-wei-yun-s-cw8x/
来源:力扣(LeetCode)https://leetcode-cn.com/problems/powx-n/

猜你喜欢

转载自blog.csdn.net/weixin_44414948/article/details/113820505
今日推荐