Convert Binary Number in a Linked List to Integer

easy linked list bit manipulation

Problem

Given the head of a singly linked list where each node holds a binary digit (0 or 1), the list represents a binary number with the most significant bit at the head. Return the integer value.

Inputhead = 1 → 0 → 1
Output5
Binary 101 is decimal 5. Walk left-to-right: 0, 1, 10 (=2), 101 (=5).

def get_decimal_value(head):
    acc = 0
    node = head
    while node:
        acc = (acc << 1) | node.val
        node = node.next
    return acc
function getDecimalValue(head) {
  let acc = 0;
  for (let node = head; node; node = node.next) {
    acc = (acc << 1) | node.val;
  }
  return acc;
}
class Solution {
    public int getDecimalValue(ListNode head) {
        int acc = 0;
        for (ListNode node = head; node != null; node = node.next) {
            acc = (acc << 1) | node.val;
        }
        return acc;
    }
}
int getDecimalValue(ListNode* head) {
    int acc = 0;
    for (ListNode* node = head; node; node = node->next) {
        acc = (acc << 1) | node->val;
    }
    return acc;
}
Time: O(n) Space: O(1)