Skip to content

Commit 06c5ff8

Browse files
committed
Adding Efficient Solution for Problem - 1290 - Convert Binary Number To Integer
1 parent 279abd6 commit 06c5ff8

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
##==================================
2+
## Leetcode
3+
## Student: Vandit Jyotindra Gajjar
4+
## Year: 2020
5+
## Problem: 1290
6+
## Problem Name: Convert Binary Number in a Linked List to Integer
7+
##===================================
8+
#
9+
#Given head which is a reference node to a singly-linked list.
10+
#The value of each node in the linked list is either 0 or 1.
11+
#The linked list holds the binary representation of a number.
12+
#
13+
#Return the decimal value of the number in the linked list.
14+
#
15+
#Example 1:
16+
#
17+
#Input: head = [1,0,1]
18+
#Output: 5
19+
#Explanation: (101) in base 2 = (5) in base 10
20+
#
21+
#Example 2:
22+
#
23+
#Input: head = [0]
24+
#Output: 0
25+
#
26+
#Example 3:
27+
#
28+
#Input: head = [1]
29+
#Output: 1
30+
#
31+
#Example 4:
32+
#
33+
#Input: head = [1,0,0,1,0,0,1,1,1,0,0,0,0,0,0]
34+
#Output: 18880
35+
#
36+
#Example 5:
37+
#
38+
#Input: head = [0,0]
39+
#Output: 0
40+
class Solution:
41+
def getDecimalValue(self, head):
42+
value = 0 #Initialize value
43+
while head: #While head is not empty
44+
value = (value)*(2) + head.value #Counting value based on given equation
45+
head = head.next #Traversing
46+
return value #Return the value
47+
#Example:
48+
#head = [1, 0, 1]
49+
#value = 0
50+
#While Loop start:
51+
#--------
52+
#head = [1, 0, 1]
53+
#value = (0)*2 + 1 = 1
54+
#--------
55+
#head = [0, 1]
56+
#value = (1)*2 + 0 = 2
57+
#--------
58+
#head = [1]
59+
#value = (2)*2 + 1 = 5
60+
#--------
61+
#head = None
62+
#value = 5

0 commit comments

Comments
 (0)