Convert a binary number stored in a linked list into its decimal integer value.
Convert Binary Number in a Linked List to Integer
You are given the head of a singly linked list where each node contains either 0 or 1. The linked list represents a binary number, with the most significant bit at the head of the list and the least significant bit at the tail.
Write a function that returns the decimal integer value of the binary number represented by the linked list.
For example, the list 1 -> 0 -> 1 represents binary 101, which is decimal 5.
Input Format
- A singly linked list head node.
- Each node stores one binary digit:
0or1.
Output Format
- Return the integer value of the binary number encoded by the list.
Constraints
- The linked list contains at least one node.
- Each node value is either
0or1. - The length of the list is small enough that the answer fits in a standard integer type.
Hints
- Traverse the list once while building the answer.
- When you move to the next bit, the current value can be shifted left by 1 before adding the new digit.
Input Format
A singly linked list head node where each node contains a binary digit (0 or 1).
Output Format
Return the decimal integer value represented by the linked list.
Constraints
- At least one node is present.
- Node values are only
0or1. - The final answer fits in a standard integer type.
Example 1
Input
head = [1,0,1]
Output
5
Explanation
Binary 101 equals decimal 5.
Example 2
Input
head = [0]
Output
0
Explanation
Binary 0 equals decimal 0.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.