↓Skip to main content
  1. LeetCode/

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

·2 mins· ·
LeetCode Easy Linked-List Bit-Manipulation Math
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2025-07-14

  • Submissions: Accepted (first try)

Approach
#

The linked list holds a binary number from the most significant bit to the least.

My Solution: store in an array, then compute backwards
#

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

Correct, but it uses an extra array and a reversal.

Better: compute while walking
#

Starting from the most significant bit, shift the result left by one (multiply by 2) for each new bit, then add the bit. It is the same idea as decimal 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

Complexity
#

Time O(n), space O(1).

Mistakes to Avoid
#

  • Accumulating 2 ** i from the head: the head is the most significant bit, not the least, so you would need the length or a reversal first.

Interview Explanation
#

The list starts at the most significant bit, so I compute while walking: for each bit, shift the result left by one and add the bit; at the tail, that is the answer. No array or length is needed, so time is O(n) and space O(1).

Related

LeetCode 762: Prime Number of Set Bits in Binary Representation
·1 min
LeetCode Easy Math Bit-Manipulation Primality-Test
LeetCode 762 note: numbers are below 10^6 < 2^20, so the set-bit count is at most 19; check it against a small set of primes
LeetCode 342: Power of Four
·1 min
LeetCode Easy Math Bit-Manipulation Recursion
LeetCode 342 note: confirm a power of two, then that the single 1 sits at an even position: n & 0x55555555 != 0, or n % 3 == 1
LeetCode 405: Convert a Number to Hexadecimal
·2 mins
LeetCode Easy Math String Bit-Manipulation
LeetCode 405 note: add 2^32 to a negative number to get its two’s complement, then take 4 bits at a time (% 16); handle 0 separately
LeetCode 231: Power of Two
·2 mins
LeetCode Easy Math Bit-Manipulation Recursion
LeetCode 231 note: a power of two has exactly one set bit, and n & (n - 1) clears the lowest one, so the result is 0 exactly then; n must be positive
LeetCode 67: Add Binary
·2 mins
LeetCode Easy Math String Bit-Manipulation Simulation
LeetCode 67 note: add from the ends of both strings digit by digit, with carry sum // 2 and digit sum % 2
LeetCode 3550: Smallest Index With Digit Sum Equal to Index
·1 min
LeetCode Easy Math Array
LeetCode 3550 note: check indices in increasing order, computing each digit sum; the first match is the answer