This is my eighth submission to the challenge. The problem today is 1290. 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.
Here is my solution:
class Solution:
def getDecimalValue(self, head: Optional[ListNode]) -> int:
binary = ""
while head.next:
binary += str(head.val)
head = head.next
binary += str(head.val)
decimal = 0
size = len(binary)
for i in range(0, size):
decimal += int(binary[i]) * 2**(size - i - 1)
return decimal
Is there a better way to do this? Please let me know.
Top comments (0)