Convert Binary Number in a Linked List to Integer In Java
Objective:
You are given the head
of a singly linked list.
Each node in the list stores a binary digit: either 0
or 1
.
This linked list represents a binary number, where the most significant bit (MSB) is at the start (head) of the list, and the least significant bit (LSB) is at the end.
Your task is to:
👉 Convert this binary number into its decimal (base-10) equivalent
👉 And return that integer value
Solution:
class Solution {
public int getDecimalValue(ListNode head) {
int result =0;
while(head!=null) {
result = result*2+head.val;
head = head.next;
}
return result;
}
}
Explanation:
- Starts with result=0;
- Traverse the list
1. Multiply current ‘result’ by 2 (left shift)
2. Add the curent node’s value (0 or 1) - It mimics converting binary to decimal by shifting and adding bits
For Ex:
Linked List: 1 -> 0 -> 1
Step By Step:
result = 0
result = 0*2+1 =1
result = 1*2+0 = 2
result = 2*2+1 = 5
So the final result is: 5