-
Notifications
You must be signed in to change notification settings - Fork 5
/
LC_1290_ConvertBinaryToInteger_LL.cpp
50 lines (41 loc) · 1.21 KB
/
LC_1290_ConvertBinaryToInteger_LL.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
42
43
44
45
46
47
48
49
50
/*
https://leetcode.com/problems/convert-binary-number-in-a-linked-list-to-integer/
1290. Convert Binary Number in a Linked List to Integer
*/
/**
* 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:
int getDecimalValue(ListNode* head) {
int decimal=0;
ListNode* ptr = head;
// Left Shifting.
// while(ptr){
// decimal*=2; // left shifting is multiply by 2
// decimal += ptr->val ; // at the time of addition it is the LSB.
// ptr = ptr->next;
// }
// return decimal;
//Using String
// string d;
// while(ptr){
// d += to_string(ptr->val) ;
// ptr = ptr->next;
// }
// return stoi(d, nullptr, 2);
while(ptr){
decimal = decimal <<1;
decimal = decimal | ptr->val;
ptr = ptr->next;
}
return decimal;
} //getDecimalValue
};