Python pow(x,n) Leetcode NO.50 分而治之
class Solution(object):
def myPow(self, x, n):
"""
:type x: float
:type n: int
:rtype: float
"""
if n == 0:
return 1
if n <0 :
return 1/self.myPow(x,-n)
if n%2 ==1:
return x*self.myPow(x,n-1)
return self.myPow(x*x,n/2)
class Solution(object):
def myPow(self, x, n):
"""
:type x: float
:type n: int
:rtype: float
"""
if n <0 :
x = 1/x
n = -n
p = 1
#&位运算,>>向右移动1位(也就是除以2)
while n:
if n & 1:
p *= x
x *= x
n >>=1
return p

本文深入解析了快速幂算法,一种高效计算指数运算的方法。通过递归和位运算两种实现方式,展示了如何在Python中利用快速幂算法解决LeetCode第50题。递归法采用分而治之策略,位运算法则利用二进制特性,两者均大幅提升了计算效率。
592

被折叠的 条评论
为什么被折叠?



