题目:
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/