递归
分治思想,二分
def myPow(self, x: float, n: int) -> float:
def quick_pow(x,n):
if n==1:
return x
half=quick_pow(x,n//2)
y=half*half if n%2==0 else half*half*x
return y
if n==0:
return 1.0
if n<0:
return quick_pow(1/x,-n)
else:
return quick_pow(x,n)
迭代
把n换成二进制
推到下x的n次幂就明白了
def myPow(self, x: float, n: int) -> float:
if n<0:
x=1/x
n=-n
if n==0:
return 1
contribute=x
res=1
while n>0:
if n&1==1:
res*=contribute
contribute*=contribute
n=n>>1
return res