# [Leet Code] Convert Binary Number in a Linked List to Integer

Problem:

`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.`

Example 1:

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

Example 2:

`Input: head = [0]Output: 0`

Solution:

`# Definition for singly-linked list.# class ListNode(object):#     def __init__(self, val=0, next=None):#         self.val = val#         self.next = nextclass Solution(object):    def getDecimalValue(self, head):        """        :type head: ListNode        :rtype: int        """        answers = []                while head.next:            answers.append(head.val)            head = head.next        answers.append(head.val)                length = len(answers) - 1        answers_sum = 0        for i,v in enumerate(answers):            answers_sum = answers_sum + (answers[i] * (2 ** length))            length = length - 1        return answers_sum`

Explanation:

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

[1,0,1]

(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 .

--

--

## More from Matthew Boyd

Learning, and posting my findings!