今天是紀錄LeetCode解題的第五十天
第五十題題目:Implement pow(x, n), which calculates x raised to the power n (i.e., xn).
實作pow(x,n),它計算x的n次方,即x^n
使用快速冪法,每一次把指數減半來計算
class Solution:
def myPow(self, x: float, n: int) -> float:
if n == 0:
return 1
if n < 0:
return 1 / self.myPow(x,-n)
half = self.myPow(x,n // 2)
if n % 2 == 0:
return half * half
else:
return half * half * x
