Problem Description
Given a singly-linked list where each node's value is either 0 or 1, the linked list represents the binary number with the most significant bit at the head. The task is to convert this binary number to its corresponding decimal (base 10) integer.
Key Insights
- The linked list contains digits of a binary number, with the head being the most significant bit.
- As you traverse the list, you can simulate binary-to-decimal conversion by shifting the current result left (multiplying by 2) and adding the current node's value.
- The linked list length is small (at most 30 nodes), which simplifies concerns about performance or overflow.
Space and Time Complexity
Time Complexity: O(n), where n is the number of nodes in the linked list.
Space Complexity: O(1), using only constant space for computations.
Solution
We iterate through the linked list and maintain an accumulator to build the decimal value. At each node, we multiply the accumulator by 2 (simulating a left bit shift) and add the node's binary digit (0 or 1). This approach directly converts the binary representation into its decimal form and completes in a single pass through the list.
Code Solutions
Python:
JavaScript:
C++:
Java: