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:
|
|
Explanation
Initialization: We initialize a variable
num
to 0. This variable will hold the decimal value of the binary number represented by the linked list.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
becomesNone
).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.Advancing to the Next Node: Inside the loop, we move to the next node by updating
head
tohead.next
.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.