Convert Binary Number in a Linked List to Integer — LeetCode 1290 Python Solution

EasyLinked ListMath
Problem
#1290
Reading time
2 min

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

Example

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

Python solution

Python
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def getDecimalValue(self, head: ListNode) -> int:
        ans = 0
        while head:
            ans = ans << 1 | head.val
            head = head.next
        return ans

Complexity

MeasureComplexity
TimeO(n), where n is the length of the linked list
SpaceO(1) auxiliary

Pattern: Linked List

Rewire pointers in place, with a dummy head and a saved next to keep it safe. LeetCode 1290. Convert Binary Number in a Linked List to Integer is filed here because LeetCode tags it Linked List, which is the vocabulary this hub collects.

The linked list guide has the Python template for the pattern and the 75 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1290. Convert Binary Number in a Linked List to Integer?
LeetCode 1290. Convert Binary Number in a Linked List to Integer is rated Easy on LeetCode.
What is the time complexity of LeetCode 1290. Convert Binary Number in a Linked List to Integer?
The Python solution on this page runs in O(n), where n is the length of the linked list.
What is the space complexity of LeetCode 1290. Convert Binary Number in a Linked List to Integer?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 1290. Convert Binary Number in a Linked List to Integer cover?
LeetCode 1290. Convert Binary Number in a Linked List to Integer is tagged Linked List and Math on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview