1.python自带方法实现:pow(x,n)
2.python自带的幂运算底层实现:x**n
在python中*n表示连续拼接几次,在这里就直接表示连续乘n次
3.减少循环次数:用递归方式,要考虑几点:(1)n=0的时候;(2)n为偶数的时候,循环次数减少一半;(3)n为奇数的时候,循环次数为(n-1)的一半加1次
class Solution(object):
def myPow(self, x, n):
"""
:type x: float
:type n: int
:rtype: float
"""
if not n:
return 1
if n<0:
return self.myPow(1/x,-n)
if n%2:
return x*self.myPow(x,n-1)
return self.myPow(x*x,n/2)