LeetCode50. Pow(x, n)(二进制位运算)

题目描述

实现 pow(x, n) ,即计算 x 的 n 次幂函数。
在这里插入图片描述

思路

详见链接

代码

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:    #按位与运算判断奇偶,奇1,偶0
				res *= x
			x *= x
			n >>= 1     #右移(除2)
		return res
发布了173 篇原创文章 · 获赞 505 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_37763870/article/details/105019307