思路:
分而治之实现O(logn)求解
利用位运算,让它节省点常数时间
代码:
处理奇偶数是关键,那两行也可以调换顺序
class Solution(object):
def myPow(self, x, n):
"""
:type x: float
:type n: int
:rtype: float
"""
# 直接递归(类似于求阶乘)和直接求时间复杂度会是O(n)会超时的
if not n:
return 1
if n < 0:
return 1 / self.myPow(x, -n)
# 偶数
if not n & 1:
# 偶数n所以除以2是整数
return self.myPow(x*x, n >> 1)
# 奇数
else:
return x * self.myPow(x, n-1)