Leetcode #1290: Convert Binary Number in a Linked List to Integer
In this guide, we solve Leetcode #1290 Convert Binary Number in a Linked List to Integer in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Easy
- Premium: No
- Tags: Linked List, Math
Intuition
There is a mathematical invariant or formula that directly leads to the result.
Using math avoids unnecessary loops and reduces complexity.
Approach
Derive the formula or update rule, then compute the answer directly.
Handle edge cases like overflow or zero carefully.
Steps:
- Identify the math relationship.
- Compute the result with a loop or formula.
- Handle edge cases.
Example
Input: head = [1,0,1]
Output: 5
Explanation: (101) in base 2 = (5) in base 10
Python Solution
# 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
The time complexity is , where is the length of the linked list. The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.