-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQuestion30.cpp
41 lines (39 loc) · 958 Bytes
/
Question30.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
30 -> Convert Binary Number in a Linked List to Integer
Solution :
/**
* 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:
ListNode*reverse(ListNode*head){
if(head==NULL)return head;
ListNode*curr=head;
ListNode*prev=NULL;
ListNode*forward=NULL;
while(curr){
forward=curr->next;
curr->next=prev;
prev=curr;
curr=forward;
}
return prev;
}
int getDecimalValue(ListNode* head) {
head=reverse(head);
ListNode*curr=head;
int ans=0,i=0;
while(curr){
ans=ans+pow(2,i)*curr->val;
i++;
curr=curr->next;
}
return ans;
}
};