Leetcode 1290. Convert Binary Number in a Linked List to Integer
Given the head of a singly linked list where each node contains a single binary digit (0 or 1), return the decimal value of the number in the linked list.
head = [1,0,1]
5
#include <iostream>
// Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
int getDecimalValue(ListNode* head) {
int result = 0;
ListNode* current = head;
while (current != nullptr) {
result = (result << 1) | current->val; // Shift left and add current node's value
current = current->next;
}
return result;
}
};
int main() {
// Example usage:
Solution solution;
// Creating the linked list [1,0,1]
ListNode* head = new ListNode(1);
head->next = new ListNode(0);
head->next->next = new ListNode(1);
// Output should be 5
std::cout << "Decimal Value: " << solution.getDecimalValue(head) << std::endl;
// Freeing the linked list
while (head != nullptr) {
ListNode* temp = head;
head = head->next;
delete temp;
}
return 0;
}
The time complexity of this function is O(n) where n is the number of nodes in the linked list. This is because we need to traverse the entire linked list once to compute the decimal value.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?