Skip to content

Commit 7a73813

Browse files
authored
Create 1290. Convert Binary Number in a Linked List to Integer (#840)
2 parents 28ce41d + a62ddd7 commit 7a73813

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* struct ListNode {
4+
* int val;
5+
* ListNode *next;
6+
* ListNode() : val(0), next(nullptr) {}
7+
* ListNode(int x) : val(x), next(nullptr) {}
8+
* ListNode(int x, ListNode *next) : val(x), next(next) {}
9+
* };
10+
*/
11+
class Solution {
12+
public:
13+
int getDecimalValue(ListNode* head) {
14+
int result = 0; // Initialize result to store decimal value
15+
16+
// Traverse the linked list from head to tail
17+
while (head != nullptr) {
18+
// Shift result left by 1 bit (multiply by 2) and add current bit
19+
result = result * 2 + head->val;
20+
21+
// Move to the next node
22+
head = head->next;
23+
}
24+
25+
return result; // Return the final decimal value
26+
}
27+
};

0 commit comments

Comments
 (0)