[Leetcode] 1290. Convert Binary Number in a Linked List to Integer

whitehousechef·2025년 7월 14일

https://leetcode.com/problems/convert-binary-number-in-a-linked-list-to-integer/description/?envType=daily-question&envId=2025-07-14

initial

ez, just like how u would solve

class Solution:
    def getDecimalValue(self, head: Optional[ListNode]) -> int:
        bin_string=""
        while head:
            bin_string+=str(head.val)
            head=head.next
        ans=0
        power=0
        for i in range(len(bin_string)-1,-1,-1):
            if bin_string[i]=="1":
                ans+= 2**power
            power+=1
        return ans

sol

but we can actually use a trick to iter from msb to lsb. If the value is 1, we can shift the accumulated value one bit to the left via ans = ans *2 .

For example if we had binary "10" and the current bit is 1, we need to shift 10 to the left and make it 100. Thats what ans*2 is doing. Then we just add a one if current bit is 1

class Solution:
    def getDecimalValue(self, head: ListNode) -> int:
        answer = 0
        while head: 
            answer = 2*answer + head.val 
            head = head.next 
        return answer 

complexity

n time
n space my code

0개의 댓글