[LeetCode]#1290. Convert Binary Number in a Linked List to Integer

Input: head = [1,0,1]
Output: 5
Explanation: (101) in base 2 = (5) in base 10
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class LinkList:
def __init__(self):
self.head=None
def initList(self, data):
# Creat head node
self.head = ListNode(data[0])
r=self.head
p = self.head
# Create node for every data
for i in data[1:]:
node = ListNode(i)
p.next = node
p = p.next
return r
def printlist(self,head):
if head == None: return
node = head
while node != None:
#print(node.val,end=' ')
node = node.next
  1. Convert n to list-node.
  2. Calculate binary to decimal based on location.
class Solution:
def getDecimalValue(self, head):
t, node_n=head, 0
while(t):
node_n+=1
t=t.next
sum_n=0
for i in range(node_n):
x=head.val
sum_n+=x*2**(node_n-1-i)
head=head.next
return sum_n

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store