實現 pow(x, n),計算 x 的 n 次冪。n 可為負數。
示例:2^-1 = 0.5,2.1^2 = 4.41。
將指數 n 拆解為二進制,利用 x^n = (x^2)^(n/2) 迭代平方。
例:2^8 = ((2^2)^2)^2,只需 3 次乘法,而非 7 次。
算法:
n < 0,取 x = 1/x,n = -n。res = 1。n > 0:
n & 1:res *= x。x *= x,n >>= 1。res。class Solution:
def myPow(self, x: float, n: int) -> float:
if n < 0:
x = 1 / x
n = -n
res = 1.0
while n:
if n & 1:
res *= x
x *= x
n >>= 1
return res
# 測試
if __name__ == "__main__":
assert Solution().myPow(2, -1) == 0.5
assert Solution().myPow(2.1, 2) == 4.41
O(log n),每次循環指數減半。O(1)。long long 存儲 n 避免 INT_MIN 取絕對值溢出。1e-5 相對誤差。