Convert Binary Number in Linked List to Integer — Bit Shift

Sanjeev SharmaSanjeev Sharma
1 min read

Advertisement

Problem 214 · Convert Binary Number in Linked List to Integer

Difficulty: Easy · Pattern: Bit Accumulation

Solutions

# Python
def getDecimalValue(head):
    num = 0
    while head:
        num = (num << 1) | head.val
        head = head.next
    return num
// Java
public int getDecimalValue(ListNode head) {
    int num = 0;
    while (head != null) { num = (num << 1) | head.val; head = head.next; }
    return num;
}
// C++
int getDecimalValue(ListNode* head) {
    int num = 0;
    while (head) { num = (num << 1) | head->val; head = head->next; }
    return num;
}

Complexity

  • Time: O(n)
  • Space: O(1)

Advertisement

Sanjeev Sharma

Written by

Sanjeev Sharma

Full Stack Engineer · E-mopro