[
linked list
bit manipulation
]
Leetcode 1290. Convert Binary Number in a Linked List to Integer
https://leetcode.com/problems/convert-binary-number-in-a-linked-list-to-integer
What we need to do in this problem is just to understand how binary numbers work. Imagine, that we have number 101100
. Then, it is equal to 1*2^5 + 0*2^4 + 1*2^3 + 1*2^2 + 0*2^1 + 0^2^0
.
So what we need to do is just to iterate over our linked list, multiply current s
by 2
and add value of new element!
Complexity: time complexity is O(n)
, where n
is length of our linked list and space complexity is O(1)
.
class Solution:
def getDecimalValue(self, head):
s = 0
while head:
s = 2*s + head.val
head = head.next
return s
If you like the solution, you can upvote it on leetcode discussion section: Problem 1290