Find the decimal number from the linked list representation of its binary form !

Input: head = [1,0,1] Output: 5 Explanation: (101) in base 2 = (5) in base 10
/*** 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;elserev(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