Convert Binary Number in a Linked List to Integer - Problem

Given the head of a singly-linked list where each node contains either 0 or 1, convert the binary number represented by the linked list to its decimal equivalent.

The binary representation follows the standard format where the most significant bit (MSB) is at the head of the list, and the least significant bit (LSB) is at the tail.

Example: If the linked list contains 1 โ†’ 0 โ†’ 1, this represents the binary number 101, which equals 5 in decimal.

Your task: Traverse the linked list and compute the decimal value efficiently.

Input & Output

example_1.py โ€” Basic Case
$ Input: head = [1,0,1]
โ€บ Output: 5
๐Ÿ’ก Note: Binary 101 equals 1ร—2ยฒ + 0ร—2ยน + 1ร—2โฐ = 4 + 0 + 1 = 5
example_2.py โ€” Single Node
$ Input: head = [0]
โ€บ Output: 0
๐Ÿ’ก Note: Single node with value 0 represents binary 0, which equals 0 in decimal
example_3.py โ€” All Ones
$ Input: head = [1,1,1,1]
โ€บ Output: 15
๐Ÿ’ก Note: Binary 1111 equals 1ร—2ยณ + 1ร—2ยฒ + 1ร—2ยน + 1ร—2โฐ = 8 + 4 + 2 + 1 = 15

Constraints

  • The number of nodes in the linked list is in the range [1, 30]
  • Node.val is either 0 or 1
  • The most significant bit is at the head of the linked list
  • The represented binary number will fit in a 32-bit integer

Visualization

Tap to expand
Binary to Decimal: One-Pass AlgorithmBinary Input:1MSB01LSBAlgorithm Steps:Step 1: result = 00Step 2: result = 0 ร— 2 + 1 = 11Step 3: result = 1 ร— 2 + 0 = 22Step 4: result = 2 ร— 2 + 1 = 55Mathematical Verification:Binary 101 = 1ร—2ยฒ + 0ร—2ยน + 1ร—2โฐ = 1ร—4 + 0ร—2 + 1ร—1 = 4 + 0 + 1 = 5 โœ“๐Ÿš— Odometer AnalogyLike reading a car's odometer from left to right, each new digitextends our number: multiply by base (2) and add the new digit!
Understanding the Visualization
1
Initialize
Start with result = 0, ready to process the first bit
2
Process Bit 1
result = 0 ร— 2 + 1 = 1 (we now have decimal 1)
3
Process Bit 0
result = 1 ร— 2 + 0 = 2 (shifted left, added 0)
4
Process Bit 1
result = 2 ร— 2 + 1 = 5 (final result!)
Key Takeaway
๐ŸŽฏ Key Insight: Instead of calculating powers of 2, we can build the decimal value incrementally using the formula `result = result ร— 2 + current_bit`, which is both more intuitive and more efficient!
Asked in
Amazon 15 Microsoft 12 Google 8 Apple 6
95.4K Views
Medium Frequency
~8 min Avg. Time
3.4K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen