# 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){
for(int i = 1; i<v.size(); i++){
while(ptr->next != NULL){
ptr = ptr->next;
}
ptr->next = new ListNode(v[i]);
}
}
class Solution {
public:
vector <int> getVector(ListNode* node){
vector <int> result;
while(node){
result.push_back(node->val);
node = node->next;
}
return result;
}
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};
}
[1,0,1,1,0,1]
45