↓快轉到主要內容
  1. LeetCode/

LeetCode 1290: Convert Binary Number in a Linked List to Integer

·1 分鐘· ·
LeetCode Easy Linked-List Bit-Manipulation Math
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: easy 第一次嘗試:2025-07-14

  • 提交紀錄:Accepted(一次通過)

解題思路
#

Linked list 從最高位排到最低位,表示一個二進位數。

我的解法:先存成陣列,再反過來算
#

values = []
while head:
    values.append(head.val)
    head = head.next
res = 0
for i, bit in enumerate(values[::-1]):
    res += bit * (2 ** i)

正確,但多用了一個陣列,還要反轉。

更好的寫法:邊走邊算
#

從最高位開始,每讀到一個新位元,就把目前的結果左移一位(乘 2),再加上這個位元。跟十進位「123 = ((1 × 10) + 2) × 10 + 3」是同一個想法:

class Solution:
    def getDecimalValue(self, head: Optional[ListNode]) -> int:
        res = 0
        while head:
            res = (res << 1) | head.val
            head = head.next
        return res

複雜度
#

時間 O(n),空間 O(1)。

要特別避免的錯誤
#

  • 從頭開始用 2 ** i 累加:頭是最高位,不是最低位,要先知道長度或反轉。

面試口說整理
#

Linked list 從最高位排起,所以我邊走邊算:每讀到一個位元,就把目前的結果左移一位再加上它,走到尾就是答案。不需要先存陣列或知道長度,時間 O(n)、空間 O(1)。

相關文章

LeetCode 762: Prime Number of Set Bits in Binary Representation
·1 分鐘
LeetCode Easy Math Bit-Manipulation Primality-Test
LeetCode 762 解題筆記:數字最多 10^6 < 2^20,1 的個數最多 19,直接比對小質數集合
LeetCode 342: Power of Four
·1 分鐘
LeetCode Easy Math Bit-Manipulation Recursion
LeetCode 342 解題筆記:先確認是 2 的次方,再確認那個 1 在偶數位:n & 0x55555555 != 0,或 n % 3 == 1
LeetCode 405: Convert a Number to Hexadecimal
·1 分鐘
LeetCode Easy Math String Bit-Manipulation
LeetCode 405 解題筆記:負數先加上 2^32 變成補數,再每次取 4 個位元(% 16)轉成十六進位;0 要特別處理
LeetCode 231: Power of Two
·1 分鐘
LeetCode Easy Math Bit-Manipulation Recursion
LeetCode 231 解題筆記:2 的次方只有一個位元是 1,n & (n - 1) 會把最低的 1 消掉,結果是 0 就是;n 要是正數
LeetCode 67: Add Binary
·1 分鐘
LeetCode Easy Math String Bit-Manipulation Simulation
LeetCode 67 解題筆記:從兩個字串的尾巴往前逐位相加,進位是 sum // 2,這一位是 sum % 2
LeetCode 3550: Smallest Index With Digit Sum Equal to Index
·1 分鐘
LeetCode Easy Math Array
LeetCode 3550 解題筆記:由小到大檢查每個 index,算位數和,第一個相等的就是答案