iT邦幫忙

0

解LeetCode的學習筆記Day50_Pow(x, n)

LFI 2025-11-10 21:11:14203 瀏覽
  • 分享至 

  • xImage
  •  

今天是紀錄LeetCode解題的第五十天

第五十題題目:Implement pow(x, n), which calculates x raised to the power n (i.e., xn).

實作pow(x,n),它計算x的n次方,即x^n

解題思路

使用快速冪法,每一次把指數減半來計算
https://ithelp.ithome.com.tw/upload/images/20251110/20179234MudpZmwAlY.png

程式碼

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

執行過程(x = 2、n = 10)

https://ithelp.ithome.com.tw/upload/images/20251110/20179234nEHVG2FLYC.png


圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言