Convert Binary Number in a Linked List to Integer
You get the head of a singly linked list. Each node stores 0 or 1. Treat the list from head to tail as the bits of a binary number, most significant bit at the head. Return the integer value in decimal.
The answer fits in a normal integer for the given constraints.
Example 1
- Input:
head = [1, 0, 1] - Output:
5(binary101is5)
Example 2
- Input:
head = [0] - Output:
0
Constraints
- The list has between
1and30nodes - Each
Node.valis0or1
Sample Input
—
Sample Output
—
Constraints
- 1 to 30 nodes
- Node.val is 0 or 1
Test Cases
Case 1
Args: [[1,0,1]]
Expected: 5
Case 2
Args: [[0]]
Expected: 0
Topics
Bit Shift Traversal
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.