题目:
思路+代码:
思路: n & 1 等价于 n % 2
n >>= 1 等价于 n //= 2
利用二分法;每次和自己相乘;因为n//2最终都会==1,所以res *=1 能取最终结果
时间复杂度:O(logn)
空间复杂度:O(1)
class Solution:
def myPow(self, x: float, n: int) -> float:
# 思路:n & 1 ==1 等价于 n % 2 ==1;
# n >>= 1 等价于 n //= 2
# 利用二分法;每次和自己相乘;因为n//2最终都会==1,所以res *=1 能取最终结果
if x == 0: return 0
if n < 0: x, n = 1/x, -n # 如果n<0, 初始化x=1/x, n=-n
res = 1
while n:
if n & 1 ==1:
res *= x
x *= x
n >>= 1
return res