[Leet Code] 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.
Input: head = [1,0,1]
Explanation: (101) in base 2 = (5) in base 10
Input: head = 
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
def getDecimalValue(self, head):
:type head: ListNode
answers = 
head = head.next
length = len(answers) - 1
answers_sum = 0
for i,v in enumerate(answers):
answers_sum = answers_sum + (answers[i] * (2 ** length))
length = length - 1
So we can break this problem into two sections, first we need to iterate over the linked list, and feed this into a string or a list. Then when we’ve done that, we then need to do the calculation for binary → decimal which is
(2² * 1) + (2¹ *0) + (2⁰*1)
4 +1 + 0 = 5
Something to note about this is that the power is len -1 of the array each time .