Binary to decimal conversion from a linkedlist binary data stream.

/* Below global variable is declared in code for modulo arithmetic
const long long unsigned int MOD = 1000000007; */

/* Link list Node/
struct Node
{
    bool data;   // NOTE data is bool
    struct Node* next;
}; */

// Should return decimal equivalent modulo 1000000007 of binary linked list
long long unsigned int decimalValue(struct Node *head)
{
   // Your Code Here
   int cnt=-1;
   long long MOD=1000000007;
   Node *tmp=head;
   bool arr[200];
   while(tmp)
   {
       cnt+=1;
       arr[cnt]=tmp->data;
       tmp=tmp->next;
   }
   long long mult=1;
   long long res;
   if(arr[cnt])
   res=1;
   else
   res=0;
   if(cnt>0)
       for(int i=cnt-1;i>=0;i--)
       {
            mult=(mult*2)%MOD;
            mult%=MOD;
            if(arr[i])
            res=(res+mult)%MOD;
       }
    return res;
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *