50. Pow(x, n)
实现 pow(x, n) ,即计算 x 的整数 n 次幂函数(即,x^n )。
此题之所以为中等题,是因为不可以使用如下接口函数来解题,题目要求我们必须自己造轮子,那么就得通过其他更底层的方法来解题。
return pow(x, n)
方法1:递归法
class Solution:
def myPow(x,n):
def quick_pow(N):
if N==0:
return 1.0
y=quick_pow(N//2)
return y*y if N%2==0 else y*y*x
return quick_pow(n) if n>=0 else 1/(qucik_pow(-n))
方法1:迭代法
class Solution:
def myPow(x,n):
def quick_pow(N):
ans=1.0
x_contribution=x
while N>0:
if N%2==1:
ans*=x_contribution
x_contribution*=x_contribution
N//=2
return ans
return quick_pow(n) if n>=0 else 1/(quick_pow(-n))