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:
- index
0= 0 so2 x 0 + 0 = 0so u get2^0 * 0- index
1= 1 so2 x 0 + 1 = 1so u get2^1 * 0 + 2^0 * 1- index
2= 0 so2 x 1 + 0 = 2so u get2^2 * 0 + 2^1 * 1 + 2^0 * 0- index
3= 1 so2 x 2 + 1 = 5so u get2^3 * 0 + 2^2 * 1 + 2^1 * 0 + 2^0 * 1
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) {
ans *= 2;
ans += head->val;
head = head->next;
}
return ans;
}
};
complexity
- Time:
O(n)wherenis the length of the linked list withhead- Space:
O(1)
time taken
- 4 minutes and 6 seconds