Binary Linked List to Integer Visualization

1290. Convert Binary Number in a Linked List to Integer

Difficulty: Easy
Topics: Linked List, Bit Manipulation, Math
Companies: Amazon, Microsoft, Google

Problem Statement

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.

Example 1

Input: head = [1,0,1]
Output: 5
Explanation: (101) in base 2 = (5) in base 10

Example 2

Input: head = [0]
Output: 0
Problem Link: View on LeetCode ↗

Key Insight

The solution leverages the fact that binary numbers can be converted to decimal by traversing the linked list and accumulating the result:

  1. Start with result = 0
  2. For each node in the linked list:
    • Left shift result by 1 (equivalent to multiplying by 2)
    • Add the current node's value to the result
  3. Return the accumulated result
Why this works: Each left shift operation moves the existing bits to the left, making room for the new bit at the least significant position.

Approach 1: Linear Traversal with Bit Shifting

This approach directly converts the binary linked list to decimal by traversing the list once.

Algorithm Steps

  1. Initialize result to 0
  2. Traverse the linked list from head to tail:
    • Left shift result by 1 (result = result * 2)
    • Add current node's value to result (result += node.val)
  3. Return the final result
Optimal Solution
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    int getDecimalValue(ListNode* head) {
        int result = 0;
        while (head != nullptr) {
            result = (result << 1) | head->val;
            head = head->next;
        }
        return result;
    }
};
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public int getDecimalValue(ListNode head) {
        int result = 0;
        while (head != null) {
            result = (result << 1) | head.val;
            head = head.next;
        }
        return result;
    }
}
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def getDecimalValue(self, head: ListNode) -> int:
        result = 0
        while head:
            result = (result << 1) | head.val
            head = head.next
        return result
Complexity: O(n) time, O(1) space - where n is the number of nodes in the linked list

Approach 2: String Conversion

This approach converts the binary linked list to a string first, then converts the string to decimal.

Algorithm Steps

  1. Traverse the linked list and build a binary string
  2. Convert the binary string to decimal using built-in functions
  3. Return the decimal value
Alternative Solution
class Solution {
public:
    int getDecimalValue(ListNode* head) {
        string binary;
        while (head != nullptr) {
            binary += to_string(head->val);
            head = head->next;
        }
        return stoi(binary, 0, 2);
    }
};
class Solution {
    public int getDecimalValue(ListNode head) {
        StringBuilder binary = new StringBuilder();
        while (head != null) {
            binary.append(head.val);
            head = head.next;
        }
        return Integer.parseInt(binary.toString(), 2);
    }
}
class Solution:
    def getDecimalValue(self, head: ListNode) -> int:
        binary = ''
        while head:
            binary += str(head.val)
            head = head.next
        return int(binary, 2)
Complexity: O(n) time, O(n) space - requires extra space for the string

Approach Comparison

Approach Time Space Best For
Bit Shifting O(n) O(1) Optimal solution
String Conversion O(n) O(n) Readability
Recommendation: Use the bit shifting approach for optimal performance

Edge Cases

1. Single node with value 0

Input: [0] → Output: 0

2. Single node with value 1

Input: [1] → Output: 1

3. All zeros

Input: [0,0,0] → Output: 0

4. All ones

Input: [1,1,1] → Output: 7

5. Maximum length (30 nodes)

Input: [1,1,...,1] (30 times) → Output: 2^30 - 1
Note: The bit shifting approach works for the maximum constraint (30 nodes) as 2^30-1 fits within a 32-bit signed integer

Frequently Asked Questions

Why does left shifting work for binary conversion?

Left shifting by 1 is equivalent to multiplying by 2 in binary. Each shift moves the existing bits left, making room for the new bit at the least significant position.

Can we solve this recursively?

Yes, but recursion would use O(n) stack space and isn't more efficient than the iterative solution.

What's the difference between bit shifting and multiplying by 2?

Bit shifting (<<) is generally faster at the hardware level than multiplication, though modern compilers often optimize multiplication by 2 to use bit shifting.

Why not use pow() function for conversion?

Using pow() would require tracking the position of each bit, making the solution more complex without any benefit over the bit shifting approach.

How does this handle leading zeros?

The problem states the most significant bit is at the head, so leading zeros are part of the number (e.g., [0,1,0] represents binary 010 which is decimal 2).

Can this be extended to other bases?

Yes, similar approaches work for other bases by multiplying by the base instead of shifting bits.

What if the linked list is empty?

The problem constraints state the linked list is not empty, so we don't need to handle this case.

Why is the bitwise OR used instead of addition?

Bitwise OR (|) and addition (+) would work the same in this case since we're only dealing with 0 and 1, but OR is slightly more idiomatic for bit manipulation.

How would you explain this to a beginner?

Imagine reading a binary number left to right. For each digit, double your current total and add the new digit. This is exactly what the bit shifting approach does.

Can we reverse the linked list first?

Yes, but reversing would require O(n) time and space without providing any benefit over the straightforward approach.

Final Recommendation: The bit shifting approach provides the most efficient solution with optimal time and space complexity, making it ideal for this problem.