LeetCode 1290: Convert Binary Number in a Linked List to Integer Solution
Master LeetCode problem 1290 (Convert Binary Number in a Linked List to Integer), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1290. Convert Binary Number in a Linked List to Integer
Problem Explanation
Explanation:
To convert the binary number represented by a linked list to an integer, we can traverse the linked list from the head to the tail while calculating the decimal value as we go. We initialize the result as 0 and for each node, we shift the result to the left by 1 (equivalent to multiplying by 2) and add the value of the current node. By doing this for all nodes, we can reconstruct the decimal value represented by the binary linked list.
Algorithm:
- Initialize result as 0.
- Traverse the linked list from head to tail.
- For each node:
- Multiply the result by 2 (left shift) to make space for the next bit.
- Add the value of the current node to the result.
- Return the final result as the decimal value.
Time Complexity:
The time complexity of this algorithm is O(n), where n is the number of nodes in the linked list.
Space Complexity:
The space complexity is O(1) as we are using a constant amount of extra space regardless of the input size.
Solution Code
class Solution {
public int getDecimalValue(ListNode head) {
int result = 0;
while (head != null) {
result = (result << 1) + head.val;
head = head.next;
}
return result;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1290 (Convert Binary Number in a Linked List to Integer)?
This page provides optimized solutions for LeetCode problem 1290 (Convert Binary Number in a Linked List to Integer) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1290 (Convert Binary Number in a Linked List to Integer)?
The time complexity for LeetCode 1290 (Convert Binary Number in a Linked List to Integer) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1290 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1290 in Java, C++, or Python.