调参划水
# -*- coding:utf-8 -*-
class Solution:
def Power(self, base, exponent):
# write code here
return pow(base,exponent)累积相乘
显然,我们可以一个一个相乘,但是这个题的关键在于,每个数都是一样的,也就是说,1号和2号的乘积等于3号和4号的乘积
换言之,乘积可以复用,大大减少计算量
# -*- coding:utf-8 -*-
class Solution:
def Power(self, base, exponent):
# write code here
res=base
flag=1
if exponent<0:
exponent*=-1
flag=-1
elif exponent==0:
return 1
while True:
if exponent==1:
res*=base
break
res*=res
exponent=exponent//2
return res if flag==1 else 1/res 
京公网安备 11010502036488号