Given a singly linked list where each node contains either 0 or 1. The linked list represents a binary number, where the head node is the most significant bit (MSB).
Convert this binary number into its decimalequivalent. If the linked list is empty, it represents the number 0.
Since the result can be very large, return the answer modulo 109 + 7.
[Naive Approach] Using Two Traversals - O(n) Time and O(1) Space
The idea is to use two traversals of the linked list. In the first traversal, find the length of the linked list. Then, in the second traversal, assign each bit its corresponding power of 2, starting from 2^(n-1) for the MSB and decreasing the power by 1 at every node.
Traverse the linked list once and find its length n.
Calculate the highest power of 2, 2^(n-1), modulo 10^9 + 7.
Traverse the list again from the head.
For every node, add node->data × power to the result.
Divide power by 2 for the next bit and apply modulo at every step.
Return the final result modulo 10^9 + 7.
C++
#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*next;Node(intx){data=x;next=nullptr;}};// Returns the decimal value of the binary linked list.intdecimalValue(Node*head){longlongMOD=1000000007;// Modulo inverse of two, using fermat's little theoremlonglongINV2=500000004;// First traversal: find the length of the linked list.intn=0;Node*temp=head;while(temp!=nullptr){n++;temp=temp->next;}// Empty linked list represents 0.if(n==0)return0;// Calculate 2^(n-1) modulo MOD.longlongpower=1;for(inti=1;i<=n-1;i++){power=(power*2)%MOD;}// Stores the decimal value.longlongres=0;// Second traversal: calculate the positional value// of each binary bit.temp=head;while(temp!=nullptr){// Add current bit multiplied by its power of 2.res=(res+temp->data*power)%MOD;// Move to the next lower power of 2.// Multiply by modular inverse of 2 instead of// directly dividing by 2.power=(power*INV2)%MOD;temp=temp->next;}returnres;}intmain(){// Binary number: 1011Node*head=newNode(1);head->next=newNode(0);head->next->next=newNode(1);head->next->next->next=newNode(1);cout<<decimalValue(head)<<endl;return0;}
Java
importjava.util.*;classNode{intdata;Nodenext;Node(intx){data=x;next=null;}}classGFG{staticfinallongMOD=1000000007;// Modulo inverse of two, using fermat's little theoremstaticfinallongINV2=500000004;// Returns the decimal value of the binary linked list.staticintdecimalValue(Nodehead){// First traversal: find the length of the linked// list.intn=0;Nodetemp=head;while(temp!=null){n++;temp=temp.next;}// Empty linked list represents 0.if(n==0)return0;// Calculate 2^(n-1) modulo MOD.longpower=1;for(inti=1;i<=n-1;i++){power=(power*2)%MOD;}// Stores the decimal value.longres=0;// Second traversal: calculate the positional value// of each binary bit.temp=head;while(temp!=null){// Add current bit multiplied by its power of 2.res=(res+temp.data*power)%MOD;// Move to the next lower power of 2.// Multiply by modular inverse of 2 instead of// directly dividing by 2.power=(power*INV2)%MOD;temp=temp.next;}return(int)res;}publicstaticvoidmain(String[]args){// Binary number: 1011Nodehead=newNode(1);head.next=newNode(0);head.next.next=newNode(1);head.next.next.next=newNode(1);System.out.println(decimalValue(head));}}
Python
classNode:def__init__(self,x):self.data=xself.next=None# Returns the decimal value of the binary linked list.defdecimalValue(head):MOD=1000000007# Modulo inverse of two, using fermat's little theoremINV2=500000004# First traversal: find the length of the linked list.n=0temp=headwhiletempisnotNone:n+=1temp=temp.next# Empty linked list represents 0.ifn==0:return0# Calculate 2^(n-1) modulo MOD.power=1foriinrange(1,n):power=(power*2)%MOD# Stores the decimal value.res=0# Second traversal: calculate the positional value# of each binary bit.temp=headwhiletempisnotNone:# Add current bit multiplied by its power of 2.res=(res+temp.data*power)%MOD# Move to the next lower power of 2.# Multiply by modular inverse of 2 instead of# directly dividing by 2.power=(power*INV2)%MODtemp=temp.nextreturnres# Driver Codeif__name__=="__main__":# Binary number: 1011head=Node(1)head.next=Node(0)head.next.next=Node(1)head.next.next.next=Node(1)print(decimalValue(head))
C#
usingSystem;classNode{publicintdata;publicNodenext;publicNode(intx){data=x;next=null;}}classGFG{constlongMOD=1000000007;// Returns the decimal value of the binary linked list.publicstaticintdecimalValue(Nodehead){// First traversal: find the length of the linked// list.intn=0;Nodetemp=head;while(temp!=null){n++;temp=temp.next;}// Empty linked list represents 0.if(n==0)return0;// Calculate 2^(n-1) modulo MOD.longpower=1;for(inti=1;i<=n-1;i++){power=(power*2)%MOD;}// Stores the decimal value.longres=0;// Second traversal: calculate the positional value// of each binary bit.temp=head;while(temp!=null){// Add current bit multiplied by its power of 2.res=(res+temp.data*power)%MOD;// Move to the next lower power of 2.power=power/2;temp=temp.next;}return(int)res;}publicstaticvoidMain(){// Binary number: 1011Nodehead=newNode(1);head.next=newNode(0);head.next.next=newNode(1);head.next.next.next=newNode(1);Console.WriteLine(decimalValue(head));}}
JavaScript
classNode{constructor(x){this.data=x;this.next=null;}}// Returns the decimal value of the binary linked list.functiondecimalValue(head){constMOD=1000000007n;// Modulo inverse of two, using fermat's little theoremconstINV2=500000004n;// First traversal: find the length of the linked list.letn=0;lettemp=head;while(temp!==null){n++;temp=temp.next;}// Empty linked list represents 0.if(n===0)return0;// Calculate 2^(n-1) modulo MOD.letpower=1n;for(leti=1;i<=n-1;i++){power=(power*2n)%MOD;}// Stores the decimal value.letres=0n;// Second traversal: calculate the positional value// of each binary bit.temp=head;while(temp!==null){// Add current bit multiplied by its power of 2.res=(res+BigInt(temp.data)*power)%MOD;// Move to the next lower power of 2.// Multiply by modular inverse of 2 instead of// directly dividing by 2.power=(power*INV2)%MOD;temp=temp.next;}returnNumber(res);}// Driver Code// Binary number: 1011lethead=newNode(1);head.next=newNode(0);head.next.next=newNode(1);head.next.next.next=newNode(1);console.log(decimalValue(head));
Output
11
[Expected Approach] Using Single Traversal - O(n) Time and O(1) Space
The idea is to use the property of binary numbers that appending a bit is equivalent to multiplying the current value by 2 and adding the new bit.
Initialize res = 0.
Traverse the linked list from the head.
For each node, update res = (res × 2 + node->data) % MOD.
Move to the next node.
Continue until the list becomes empty and finally, return res.
Consider the following example for better understanding: 1 --> 0 --> 1 --> 1
Initialize res = 0.
For 1: res = 0 × 2 + 1 = 1
For 0: res = 1 × 2 + 0 = 2
For 1: res = 2 × 2 + 1 = 5
For 1: res = 5 × 2 + 1 = 11
So, the answer is 11.
C++
#include<iostream>usingnamespacestd;classNode{public:intdata;Node*next;Node(intval){data=val;next=nullptr;}};intdecimalValue(Node*head){constlonglongMOD=1000000007;// Stores the decimal value of the binary number.longlongres=0;// Traverse the linked list.while(head!=nullptr){// Multiply the current value by 2 and// add the current binary digit.res=(res*2+head->data)%MOD;// Move to the next node.head=head->next;}// Return the final decimal value.returnres;}intmain(){// Binary number: 1011Node*head=newNode(1);head->next=newNode(0);head->next->next=newNode(1);head->next->next->next=newNode(1);cout<<decimalValue(head)<<endl;return0;}
Java
classNode{intdata;Nodenext;Node(intval){data=val;next=null;}}classGFG{publicstaticintdecimalValue(Nodehead){finallongMOD=1000000007;// Stores the decimal value of the binary number.longres=0;// Traverse the linked list.while(head!=null){// Multiply the current value by 2 and// add the current binary digit.res=(res*2+head.data)%MOD;// Move to the next node.head=head.next;}// Return the final decimal value.return(int)res;}publicstaticvoidmain(String[]args){// Binary number: 1011Nodehead=newNode(1);head.next=newNode(0);head.next.next=newNode(1);head.next.next.next=newNode(1);System.out.println(decimalValue(head));}}
Python
classNode:def__init__(self,val):self.data=valself.next=NonedefdecimalValue(head):MOD=1000000007# Stores the decimal value of the binary number.res=0# Traverse the linked list.whileheadisnotNone:# Multiply the current value by 2 and# add the current binary digit.res=(res*2+head.data)%MOD# Move to the next node.head=head.next# Return the final decimal value.returnres# Driver Codeif__name__=="__main__":# Binary number: 1011head=Node(1)head.next=Node(0)head.next.next=Node(1)head.next.next.next=Node(1)print(decimalValue(head))
C#
usingSystem;classNode{publicintdata;publicNodenext;publicNode(intval){data=val;next=null;}}classGFG{publicstaticintdecimalValue(Nodehead){constlongMOD=1000000007;// Stores the decimal value of the binary number.longres=0;// Traverse the linked list.while(head!=null){// Multiply the current value by 2 and// add the current binary digit.res=(res*2+head.data)%MOD;// Move to the next node.head=head.next;}// Return the final decimal value.return(int)res;}publicstaticvoidMain(){// Binary number: 1011Nodehead=newNode(1);head.next=newNode(0);head.next.next=newNode(1);head.next.next.next=newNode(1);Console.WriteLine(decimalValue(head));}}
JavaScript
classNode{constructor(val){this.data=val;this.next=null;}}functiondecimalValue(head){constMOD=1000000007n;// Stores the decimal value of the binary number.letres=0n;// Traverse the linked list.while(head!==null){// Multiply the current value by 2 and// add the current binary digit.res=(res*2n+BigInt(head.data))%MOD;// Move to the next node.head=head.next;}// Return the final decimal value.returnNumber(res);}// Driver Code// Binary number: 1011lethead=newNode(1);head.next=newNode(0);head.next.next=newNode(1);head.next.next.next=newNode(1);console.log(decimalValue(head));