1290: Convert-Binary-Number-in-a-Linked-List-to-Integer
Easy
table of contents
We can simply iterate through the linked list and left shift
our answer after every iteration, adding 1
depending on
what the bit is.
Using [0, 1, 0, 1]
as an example, we have:
code
/**
* 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 ans = 0;
while (head != NULL) {
*= 2;
ans += head->val;
ans = head->next;
head }
return ans;
}
};