You are 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 decimal equivalent. If the linked list is empty, it represents the number 0. Since the result can be very large, return the answer modulo 109+7.
[Optimal Approach] Using Bit Manipulation (Left Shift) – O(n) Time and O(1) Space
The linked list represents a binary number where each node is a bit (0 or 1). We can convert it into a decimal value by traversing the list and continuously updating the result. At each step, we multiply the current result by 2 (using left shift) and add the current node’s value, which mimics binary to decimal conversion efficiently.
Initialize res = 0 to store the result.
Traverse the linked list from head to end.
For each node: Left shift the result res = res << 1 (multiply by 2), add current node value res = res + head->data and take modulo 109+710^9 + 7109+7 to prevent overflow.
#include<stdio.h>#include<stdlib.h>#define MOD 1000000007// Node structurestructNode{intdata;structNode*next;};// Create new nodestructNode*newNode(intval){structNode*node=(structNode*)malloc(sizeof(structNode));node->data=val;node->next=NULL;returnnode;}// Function to convert binary LL to decimalintdecimalValue(structNode*head){longlongres=0;while(head!=NULL){res=((res<<1)+head->data)%MOD;head=head->next;}return(int)res;}intmain(){structNode*head=newNode(1);head->next=newNode(0);head->next->next=newNode(1);head->next->next->next=newNode(1);printf("%d",decimalValue(head));return0;}
constMOD=1000000007;// Node classclassNode{constructor(val){this.data=val;this.next=null;}}// Function to convert binary LL to decimalfunctiondecimalValue(head){letres=0;while(head!==null){res=((res<<1)+head.data)%MOD;head=head.next;}returnres;}// Examplelethead=newNode(1);head.next=newNode(0);head.next.next=newNode(1);head.next.next.next=newNode(1);console.log(decimalValue(head));
Output
Decimal value is 11
[Another Approach] Using Reverse + Power Calculation – O(n log n) Time and O(n) Space (Recursion Stack)
In this approach, the linked list is first reversed so that we can process bits from least significant bit (LSB) to most significant bit (MSB). Then, for each node, we calculate its contribution using the formula bit×2(position). A fast exponentiation (power) function is used to efficiently compute powers of 2 under modulo. By summing all contributions, we get the decimal value of the binary number.
Reverse the linked list to process from LSB to MSB.
Initialize ans = 0 and pos = 0.
Traverse the reversed list:
For each node, compute power(2, pos) for its position, multiply it with current node value (0 or 1) and add it to ans with modulo.
Increment position pos after each node.
C++
#include<bits/stdc++.h>usingnamespacestd;// node structurestructNode{intdata;Node*next;Node(intdata){this->data=data;this->next=nullptr;}};// power functionlonglongunsignedintpower(intnum,intcount){if(count==0)return1;if(count%2==0){longlonghalf=power(num,count/2)%1000000007;return(half*half)%1000000007;}else{longlonghalf=power(num,count/2)%1000000007;return(num*half%1000000007*half%1000000007)%1000000007;}}// reverse linked listNode*reverse(Node*head){if(head==nullptr||head->next==nullptr)returnhead;Node*curr=head;Node*prev=nullptr;Node*nxt=head->next;while(nxt!=nullptr){curr->next=prev;prev=curr;curr=nxt;nxt=nxt->next;}curr->next=prev;returncurr;}// function to get decimal valueintdecimalValue(Node*head){intMOD=1000000007;Node*rhead=reverse(head);intans=0;intpos=0;while(rhead!=nullptr){ans=(ans%MOD+(rhead->data*power(2,pos))%MOD)%MOD;rhead=rhead->next;pos++;}returnans;}// main functionintmain(){Node*head=newNode(1);head->next=newNode(0);head->next->next=newNode(1);head->next->next->next=newNode(1);cout<<"Decimal Value is : "<<decimalValue(head);}
Java
classGFG{staticclassNode{intdata;Nodenext;Node(intdata){this.data=data;this.next=null;}}staticfinalintMOD=1000000007;// Fast power (binary exponentiation)staticlongpower(intnum,intcount){if(count==0)return1;longhalf=power(num,count/2)%MOD;if(count%2==0)return(half*half)%MOD;elsereturn(num*half%MOD*half%MOD)%MOD;}// Reverse linked liststaticNodereverse(Nodehead){Nodeprev=null,curr=head;while(curr!=null){Nodenext=curr.next;curr.next=prev;prev=curr;curr=next;}returnprev;}// Convert to decimalstaticintdecimalValue(Nodehead){Noderhead=reverse(head);longans=0;intpos=0;while(rhead!=null){ans=(ans+(rhead.data*power(2,pos))%MOD)%MOD;rhead=rhead.next;pos++;}return(int)ans;}publicstaticvoidmain(String[]args){Nodehead=newNode(1);head.next=newNode(0);head.next.next=newNode(1);head.next.next.next=newNode(1);System.out.println("Decimal Value is : "+decimalValue(head));}}
Python
MOD=1000000007classNode:def__init__(self,data):self.data=dataself.next=None# Fast powerdefpower(num,count):ifcount==0:return1half=power(num,count//2)%MODifcount%2==0:return(half*half)%MODelse:return(num*half%MOD*half%MOD)%MOD# Reverse linked listdefreverse(head):prev=Nonecurr=headwhilecurr:nxt=curr.nextcurr.next=prevprev=currcurr=nxtreturnprev# Convert to decimaldefdecimalValue(head):rhead=reverse(head)ans=0pos=0whilerhead:ans=(ans+(rhead.data*power(2,pos))%MOD)%MODrhead=rhead.nextpos+=1returnans# Examplehead=Node(1)head.next=Node(0)head.next.next=Node(1)head.next.next.next=Node(1)print("Decimal Value is:",decimalValue(head))
C#
usingSystem;classGFG{classNode{publicintdata;publicNodenext;publicNode(intdata){this.data=data;this.next=null;}}staticintMOD=1000000007;// Fast powerstaticlongPower(intnum,intcount){if(count==0)return1;longhalf=Power(num,count/2)%MOD;if(count%2==0)return(half*half)%MOD;elsereturn(num*half%MOD*half%MOD)%MOD;}// Reverse linked liststaticNodeReverse(Nodehead){Nodeprev=null,curr=head;while(curr!=null){Nodenext=curr.next;curr.next=prev;prev=curr;curr=next;}returnprev;}// Convert to decimalstaticintDecimalValue(Nodehead){Noderhead=Reverse(head);longans=0;intpos=0;while(rhead!=null){ans=(ans+(rhead.data*Power(2,pos))%MOD)%MOD;rhead=rhead.next;pos++;}return(int)ans;}staticvoidMain(){Nodehead=newNode(1);head.next=newNode(0);head.next.next=newNode(1);head.next.next.next=newNode(1);Console.WriteLine("Decimal Value is : "+DecimalValue(head));}}
JavaScript
constMOD=1000000007;// Node classclassNode{constructor(data){this.data=data;this.next=null;}}// Fast powerfunctionpower(num,count){if(count===0)return1;lethalf=power(num,Math.floor(count/2))%MOD;if(count%2===0)return(half*half)%MOD;elsereturn(num*half%MOD*half%MOD)%MOD;}// Reverse linked listfunctionreverse(head){letprev=null,curr=head;while(curr!==null){letnext=curr.next;curr.next=prev;prev=curr;curr=next;}returnprev;}// Convert to decimalfunctiondecimalValue(head){letrhead=reverse(head);letans=0;letpos=0;while(rhead!==null){ans=(ans+(rhead.data*power(2,pos))%MOD)%MOD;rhead=rhead.next;pos++;}returnans;}// Examplelethead=newNode(1);head.next=newNode(0);head.next.next=newNode(1);head.next.next.next=newNode(1);console.log("Decimal Value is :",decimalValue(head));