link list binary to decimal
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
void rev(ListNode* head, vector<int>&v)
{
if(head==0)
return;
else
rev(head->next,v);
v.push_back(head->val);
}
int getDecimalValue(ListNode* head)
{
vector<int>v;
rev(head,v);
int sum=0,i=1;
for(auto it: v){
if(it==1)
{
sum+=i;
}
i*=2;
}
return sum;
}
};
Comments
Post a Comment