Convert Binary Number in a Linked List to Integer Easy 0 attempts
LeetCode ↗

Convert Binary Number in a Linked List to Integer

Easy Linked List LeetCode

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.

Input Format
Implement getDecimalValue(head). Inputs below show JavaScript function arguments; there is no stdin parsing. Linked lists use value arrays. The editor passes nodes with val and next properties; [] becomes null.
Output Format
Return the result described in the statement.

Sample Input and Output

Example 1 ยท Run Sample

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

Example 2

Input
head = [0]
Output
0
Constraints
  • 1 to 30 nodes
  • Node.val is 0 or 1
Test Cases (2)
Case 1
Args: [[1,0,1]] Expected: 5
Case 2
Args: [[0]] Expected: 0
Topics

Bit Shift Traversal

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)

Saved in this browser only. Private to you.

JavaScript