
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Program to convert Linked list representing binary number to decimal integer in Python
Suppose we have a singly linked list. the linked list is representing a binary number with most significant digits first, we have to return it as decimal number.
So, if the input is like [1,0,1,1,0], then the output will be 22
To solve this, we will follow these steps −
- l := a new list
- while node is not null, do
- insert value of node at the end of l
- node:= next of node
- k := 0, v:= 0
- for i in range size of l - 1 to 0, decrease by 1, do
- if l[i] is same as 1, then
- v := v + 2^k
- k := k + 1
- if l[i] is same as 1, then
- return v
Let us see the following implementation to get better understanding −
Example
class ListNode: def __init__(self, data, next = None): self.val = data self.next = next def make_list(elements): head = ListNode(elements[0]) for element in elements[1:]: ptr = head while ptr.next: ptr = ptr.next ptr.next = ListNode(element) return head class Solution: def solve(self, node): l = [] while node: l.append(node.val) node=node.next k = 0 v=0 for i in range(len(l)-1,-1,-1): if (l[i]==1): v += (2**k) k+=1 return v ob = Solution() head = make_list([1,0,1,1,0]) print(ob.solve(head))
Input
[1,0,1,1,0]
Output
22
- Related Articles
- Convert Binary Number in a Linked List to Integer in C++
- Convert decimal to binary number in Python program
- Python program to convert decimal to binary number
- Program to convert linked list to zig-zag binary tree in Python
- Java Program to convert binary number to decimal number
- C++ Program To Convert Decimal Number to Binary
- Python program to convert a given binary tree to doubly linked list
- Program to convert level order binary tree traversal to linked list in Python
- Java Program to convert decimal integer to octal number
- Java Program to convert decimal integer to hexadecimal number
- Java program to convert decimal number to binary value
- Java program to convert binary number to decimal value
- C++ program to Convert a Decimal Number to Binary Number using Stacks
- Haskell program to convert a decimal number into a binary number
- Convert decimal integer to hexadecimal number in Java

Advertisements