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.valis either0or1 - 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
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!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code