#1290

Convert Binary Number in a Linked List to Integer

Easy
Linked ListMathBit ManipulationLinked List Traversal
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(n)
O(1)
💡

Intuition

Time O(n)Space O(1)

Instead of building a string, we can directly compute the decimal value while traversing the linked list. This uses bit manipulation to build the number efficiently.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a variable 'result' to 0.
  2. 2Step 2: Traverse the linked list while head is not null.
  3. 3Step 3: For each node, shift 'result' left by 1 (multiply by 2) and add the current node's value.
solution.py11 lines
1class ListNode:
2    def __init__(self, val=0, next=None):
3        self.val = val
4        self.next = next
5
6def getDecimalValue(head):
7    result = 0
8    while head:
9        result = (result << 1) | head.val
10        head = head.next
11    return result

Complexity note: The time complexity is O(n) because we traverse the linked list once. The space complexity is O(1) since we are using a constant amount of space to store the result.

  • 1Understanding binary representation and bit manipulation is crucial.
  • 2Using bitwise operations can significantly optimize performance.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.