Convert Binary Number in a Linked List to Integer — LeetCode 1290 Python Solution
EasyLinked ListMath
- Problem
- #1290
- Pattern
- Linked List
- Reading time
- 2 min
- Source
- leetcode.com
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the length of the linked list |
| Space | O(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.