原题出处:https://leetcode.cn/leetbook/read/top-interview-questions-medium/xwo102/
解法一:
class Solution:
def myPow(self, x: float, n: int) -> float:
if n == 0:
return 1
if n < 0:
x = 1 / x
n = abs(n)
res = 1
while n > 0:
if n & 1 == 1:
res *= x
x *= x
n >>= 1
return res
思路:
如果 n 等于 0,返回 1。
如果 n 是负数,将 x 变为 1/x,n 变为其绝对值。
初始化 res 为 1。
当 n 大于 0 时,进行以下操作:
如果 n 的最后一位是 1,将 res 乘以 x。
将 x 乘以自身。
将 n 右移一位,相当于 n 除以 2。
返回 res。