class Solution:
def myPow(self, x: float, n: int) -> float:
# 向下整除 n // 2 等价于 右移一位 n >> 1;
# 取余数 n % 2 等价于 判断二进制最右一位值 n & 1;
if x==0: return 0
res = 1
if n<0:
x = 1/x
n = -n
while n:
if n & 1:
# 即判断 n % 2 == 1
# 判断n为奇数还是偶数,如果为奇数,则在res的基础上乘x
res *= x
# x 平方 处理
x *= x
# n向下整除
# 即 n // 2
n >>= 1
return res
递归方法:
class Solution:
def myPow(self, x: float, n: int) -> float:
# 当n是0的时候,直接返回1即可
# 当n小于0的时候,需要把它转化为正数才能更方便计算,同时x要变为1/x
# 当n大于0的时候,要分为两种情况,一种是偶数,一种是奇数。
# 向下整除 n // 2 等价于 右移一位 n >> 1;
# 取余数 n % 2 等价于 判断二进制最右一位值 n & 1;
if n == 0:
return 1
if n < 0:
return 1/self.myPow(x,-n)
if n&1:
# 如果n为奇数
return x * self.myPow(x*x,n//2)
return self.myPow(x*x, n//2)