Implement pow(x, n), which calculates x raised to the power n (xn).
就是实现pow函数(指数函数)。
思路
重复乘以n次虽然简单,但是时间复杂度不通过。所以考虑利用已经计算出来的值多次相乘。其他就是一些特殊情况,底数为1,-1,以及上下边界等一些细枝末节的问题。
MIN_VAL = pow(-2,31)
MAX_VAL = pow(2,31)-1
class Solution:
def powHelper(self, x: float, n: int) -> float:
index = 0
res = 1
multires = 1
absn = abs(n)
while index < absn:
if n - index * index > 1 and res > 1:
index*=2
multires=res*res
else:
multires = res*x
index+=1 #乘以了index个x
if multires < MIN_VAL:
index = absn
res = float("-inf")
elif multires > MAX_VAL:
index = absn
res = float("inf")
elif multires == 0:
index = absn
res = float(0)
else:
res = multires
if n < 0:
res = 1/res
return res
def myPow(self, x: float, n: int) -> float:
if n == 0:
return float(1)
elif x == 0:
return float(0)
elif x == float(1):
return float(1)
elif x == float(-1):
if n%2 == 0:
return float(1)
else:
return -float(1)
else:
return self.powHelper(x,n)
然后这种思路也可以用递归的形式表示:
class Solution:
def myPow(self,x: float , n:int):
if(n == 0):
return 1
if(n<0):
n = -n
x = 1/x
if (n%2 == 0) :
# 若指数n为偶数,则用x*x来做底数,n/2做指数,再递归求pow
return self.myPow(x*x, n/2)
else:
# 若指数n为奇数,则用x*x来做底数,(int)(n/2)做指数,再递归求pow,然后乘以一个剩余的x
return x*self.myPow(x*x, (int)(n/2))
THE END.