Convert Binary Number in a Linked List to Integer in C++


Suppose we have one ‘head’ which is a reference node to a singly-linked list. The value of each node present in the linked list is either 0 or 1. This linked list stores the binary representation of a number. We have to return the decimal value of the number present in the linked list. So if the list is like [1,0,1,1,0,1]

To solve this, we will follow these steps −

  • x := convert the list elements into an array

  • then reverse the list x

  • ans := 0, and temp := 1

  • for i in range i := 0, to size of x – 1

    • ans := ans + x[i] * temp

    • temp := temp * 2

  • return ans

Example (C++)

Let us see the following implementation to get a better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class ListNode{
   public:
      int val;
      ListNode *next;
      ListNode(int data){
         val = data;
         next = NULL;
      }
};
ListNode *make_list(vector<int> v){
   ListNode *head = new ListNode(v[0]);
   for(int i = 1; i<v.size(); i++){
      ListNode *ptr = head;
      while(ptr->next != NULL){
         ptr = ptr->next;
      }
      ptr->next = new ListNode(v[i]);
   }
   return head;
}
class Solution {
public:
   vector <int> getVector(ListNode* node){
      vector <int> result;
      while(node){
         result.push_back(node->val);
         node = node->next;
      }
      return result;
   }
   int getDecimalValue(ListNode* head) {
      vector <int> x = getVector(head);
      reverse(x.begin(), x.end());
      int ans = 0;
      int temp = 1;
      for(int i = 0; i < x.size(); i++){
         ans += x[i] * temp;
         temp *= 2;
      }
      return ans;
   }
};
main(){
   Solution ob;
   vector<int> v = {1,0,1,1,0,1};
   ListNode *head = make_list(v);
   cout << ob.getDecimalValue(head);
}

Input

[1,0,1,1,0,1]

Output

45

Updated on: 27-Apr-2020

563 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements