{x}
blog image

Convert Binary Number in a Linked List to Integer

Given head which is a reference node to a singly-linked list. The value of each node in the linked list is either 0 or 1. The linked list holds the binary representation of a number.

Return the decimal value of the number in the linked list.

The most significant bit is at the head of the linked list.

 

Example 1:

Input: head = [1,0,1]
Output: 5
Explanation: (101) in base 2 = (5) in base 10

Example 2:

Input: head = [0]
Output: 0

 

Constraints:

  • The Linked List is not empty.
  • Number of nodes will not exceed 30.
  • Each node's value is either 0 or 1.

Solution Explanation:

This problem asks to convert the binary number represented by a linked list into its decimal equivalent. The solution utilizes bit manipulation for efficient conversion.

Approach:

The core idea is to iterate through the linked list, processing each node's value (0 or 1) to build the decimal representation. We achieve this using bitwise left shift (<<) and bitwise OR (|).

  1. Initialization: We start with a variable ans initialized to 0. This variable will store the accumulating decimal value.

  2. Iteration: We traverse the linked list using a while loop (or a for loop in some languages). In each iteration:

    • We perform a left bit shift on ans by 1 (ans << 1). This shifts all bits in ans one position to the left, effectively multiplying ans by 2. This prepares ans to incorporate the next bit from the linked list.

    • We perform a bitwise OR operation between the shifted ans and the current node's value (| head.val). This adds the current bit (0 or 1) to the least significant bit of ans.

    • We move to the next node in the linked list.

  3. Return Value: After iterating through the entire list, ans holds the final decimal value, which is returned.

Time Complexity: O(N), where N is the number of nodes in the linked list. We iterate through the list once.

Space Complexity: O(1). We use only a constant amount of extra space to store variables like ans.

Code Explanation (Python example):

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def getDecimalValue(self, head: ListNode) -> int:
        ans = 0
        while head:
            ans = ans << 1 | head.val
            head = head.next
        return ans
  • The while head: loop continues as long as head is not None (end of the list).
  • ans << 1 shifts the bits in ans to the left by one position (multiplying by 2).
  • | head.val performs a bitwise OR to add the current node's value (0 or 1) to ans.

The other language examples follow the same logic, differing only in syntax. The core algorithm remains consistent across all implementations.