Convert Binary Number in a Linked List to Integer

The problem requires us to convert a binary number represented as a singly-linked list into its decimal equivalent.

Python solution:

1
2
3
4
5
6
7
8
9
class Solution:
    def getDecimalValue(self, head: ListNode) -> int:
        num = 0

        while head:
            num = num * 2 + head.val
            head = head.next

        return num

Explanation

  1. Initialization: We initialize a variable num to 0. This variable will hold the decimal value of the binary number represented by the linked list.

  2. Iterating through the Linked List: We use a while loop to iterate through the linked list. The loop continues until we reach the end of the linked list (head becomes None).

  3. Calculating Decimal Value: Inside the loop, we multiply the current value of num by 2 (shifting the binary number to the left) and then add the value of the current node (head.val). This helps in converting the binary number to its decimal equivalent.

  4. Advancing to the Next Node: Inside the loop, we move to the next node by updating head to head.next.

  5. Returning the Result: After the loop, we return the value of num, which represents the decimal value of the binary number represented by the given linked list.