Convert Binary Number in a Linked List to Integer - Problem

Given head which is a reference node to a singly-linked list. The value of each node in the linked list is either 0 or 1. The linked list holds the binary representation of a number.

Return the decimal value of the number in the linked list. The most significant bit is at the head of the linked list.

Input & Output

Example 1 — Basic Binary Conversion
$ Input: head = [1,0,1]
Output: 5
💡 Note: Binary number 101₂ = 1×4 + 0×2 + 1×1 = 5 in decimal
Example 2 — Single Bit
$ Input: head = [0]
Output: 0
💡 Note: Single bit 0 represents decimal 0
Example 3 — Longer Binary Number
$ Input: head = [1,0,0,1,0,0,1,1,1,0,0,0,1,0,0,1,1,0,0,1,0]
Output: 1208626
💡 Note: Long binary sequence 100100111000100110010₂ converts to decimal 1208626

Constraints

  • The linked list is not empty
  • Number of nodes is in the range [1, 30]
  • Each node's value is either 0 or 1

Visualization

Tap to expand
Binary Linked List to Integer INPUT Linked List (Binary) 1 head 0 1 NULL Binary Number: 1 0 1 Bit Positions: 2^2 2^1 2^0 Input: head = [1, 0, 1] ALGORITHM STEPS 1 Initialize result = 0 Start with decimal value 0 2 Traverse linked list Visit each node from head 3 Shift and add result = result*2 + node.val 4 Return result Final decimal value Computation Trace: Node 1: 0*2 + 1 = 1 Node 0: 1*2 + 0 = 2 Node 1: 2*2 + 1 = 5 Final: 5 FINAL RESULT Binary to Decimal Conversion 1 0 1 1 x 4 0 x 2 1 x 1 4 + 0 + 1 = 5 Decimal Value: 5 Output: 5 [OK] Conversion Complete Key Insight: The formula "result = result * 2 + bit" processes binary digits left-to-right, building the decimal value incrementally. Multiplying by 2 shifts existing bits left, then adding the new bit appends it. Time: O(n) where n = number of nodes. Space: O(1) - only one variable needed. TutorialsPoint - Convert Binary Number in a Linked List to Integer | Direct Conversion Approach
Asked in
Microsoft 15 Amazon 12 Apple 8 Google 6
187.0K Views
Medium Frequency
~15 min Avg. Time
2.2K 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