< Back





1290. Convert Binary Number in a Linked List to Integer

Another simple question, doing some bit arithmetic. We traverse the linked list from the head to the
tail, and for each node, we shift the current value to the left by 1 and or the value of the current
node.

The solution is as follows:


  class Solution:
      def getDecimalValue(self, head: ListNode) -> int:
          num = head.val
          while head.next:
              num = (num << 1) | head.next.val
              head = head.next
          return num


_ Time Complexity:

  O(n) - We traverse all nodes within the linked list.

_ Space Complexity:

  O(1) - We maintain pointers that occupy constant space.