700183. Decimal Equivalent of Binary Linked List
Decimal Equivalent of Binary Linked List
Summary
This problem involves converting a binary linked list to its decimal equivalent. The key concept involved is manipulation of linked lists, specifically traversing and processing nodes in a specific order.
Detailed Explanation
To solve this problem, we can start by defining the structure of our linked list node. Each node will have an integer value and a reference to the next node in the list.
We'll begin by initializing a variable decimal_equivalent to store the decimal equivalent of the binary linked list. Then, we'll traverse the linked list and add each node's value to decimal_equivalent, shifting the bits one position to the left for each new addition.
Here's the step-by-step breakdown:
- Initialize
decimal_equivalentto 0. - Traverse the linked list:
- For each node, check if its value is 1 (binary) or 0 (not binary).
- If the value is 1, add 2 raised to the power of the current position (
2^i) todecimal_equivalent, whereiis the position of the node in the list.
- Return
decimal_equivalent.
The time complexity for this solution is O(n), where n is the number of nodes in the linked list, as we're traversing the list once. The space complexity is O(1), as we're not using any extra space that scales with the input size.
Optimized Solutions
Java
public int decimalEquivalent(BinaryNode head) {
int decimal_equivalent = 0;
int i = 0;
while (head != null) {
if (head.value == 1) {
decimal_equivalent += (int) Math.pow(2, i);
}
head = head.next;
i++;
}
return decimal_equivalent;
}