Skip to problem
←

Convert Binary Number in a Linked List to Integer

Easy 0 attempts

You're given the head of a singly linked list whose nodes each hold a single bit, 0 or 1. Reading the list from head to tail gives the binary digits of a number, with the most significant bit at the head. Convert that binary value to its decimal integer and return it.

Given the constraints below, the result always fits in a standard integer.

Function contract

Implement getDecimalValue(head). The runner turns the displayed value array into linked nodes with val and next fields; the head contains the most significant bit.

Output: The non-negative integer represented by the list’s binary digits.

Example 1

Input
head = [1,0,1]
Output
5

Explanation: Read 1 → 0 → 1 as binary 101: 1×4 + 0×2 + 1 = 5.

Example 2

Input
head = [0]
Output
0
Constraints
  • 1 to 30 nodes
  • Node.val is 0 or 1
Topics

Accumulate Bits

Double the accumulated value and add the next bit at each node.

javascript
function getDecimalValue(head) {
  let num = 0;
  while (head) { num = num * 2 + head.val; head = head.next; }
  return num;
}

Time: O(n) | Space: O(1)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript