Magicsheet logo

Convert Binary Number in a Linked List to Integer

Easy
51.2%
Updated 6/1/2025

Convert Binary Number in a Linked List to Integer

What is this problem about?

The Convert Binary Number in a Linked List to Integer interview question asks you to traverse a singly linked list where each node contains either a 0 or a 1. The sequence of values in the list represents a binary number, with the head being the most significant bit. You need to return the decimal value of this number.

Why is this asked in interviews?

This Convert Binary Number in a Linked List to Integer coding problem is a standard screening question at companies like Microsoft and Cisco. It tests basic linked list traversal and knowledge of binary-to-decimal conversion. It evaluates if a candidate can process data in a single pass without needing extra space.

Algorithmic pattern used

This follows the Linked List, Math interview pattern.

  • Decimal value V can be calculated iteratively.
  • Start with ans = 0.
  • For each node: ans = (ans * 2) + node.val.
  • This is equivalent to bit-shifting the current answer to the left and adding the new bit: ans = (ans << 1) | node.val.

Example explanation

Linked List: 1 -> 0 -> 1

  1. Head (1): ans = 0 * 2 + 1 = 1.
  2. Next (0): ans = 1 * 2 + 0 = 2.
  3. Next (1): ans = 2 * 2 + 1 = 5. Result: 5.

Common mistakes candidates make

  • String Conversion: Converting the list to a string first and then using parseInt(s, 2), which uses O(N) extra space.
  • Power of 2: Trying to calculate the length of the list first to use powers of 2 (2^(len-1) + ...). This requires two passes over the list.
  • Bitwise precedence: Not using parentheses correctly when combining bitwise shifts and OR operations.

Interview preparation tip

Always prefer the single-pass "Shift and Add" approach for binary conversion problems. It’s the most efficient way to process data where the most significant bits arrive first.

Similar Questions