递归快速幂(计算机都是通过数字的补码进行运算
所以我们需要先计算出数的补码,再将补码左移三位.然后算出反码,再算出原码)
参考:https://blog.csdn.net/m0_52424915/article/details/110525197
class Solution:
def Power(self, x, n):
if n==0:
return 1
if n < 0:
x=1/x
n=-n
if n&1:
return x*self.Power(x*x, n//2)
else:
return self.Power(x*x, n//2)
迭代快速幂:
class Solution:
def myPow(self, x, n):
res = 1
if n==0:
return 1
if n < 0:
x=1/x
n=-n
while n!= 0:
if n&1 == 1:
res *= x
x *= x
n>>=1
return res
暴力
class Solution:
def myPow(self, x, n):
if n==0: return 1
res = 1
if n < 0:
x=1/x
n=-n
for i in range(n):
res *= x
return res