본문 바로가기
python-algorithm

leetcode 1290. Convert Binary Number in a Linked List to Integer

by 무적김두칠 2023. 2. 28.

https://leetcode.com/problems/convert-binary-number-in-a-linked-list-to-integer/description/

 

Convert Binary Number in a Linked List to Integer - LeetCode

Can you solve this real interview question? Convert Binary Number in a Linked List to Integer - Given head which is a reference node to a singly-linked list. The value of each node in the linked list is either 0 or 1. The linked list holds the binary repre

leetcode.com

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def getDecimalValue(self, head: ListNode) -> int:
        node = head
        q: list = []
        while node is not None:
            q.append(str(node.val))
            node=node.next
        
        answer = int(''.join(q),2)
        return answer
cs

조건중에 linked list가 비어있는 경우는 없다고 하니 예외처리를 따로 할 필요가 없네요
list로 변환후 value들을 str로 type casting 한 후 int 함수를 이용해 return 합니다.

Among the conditions, there is no case where the linked list is empty, so there is no need for exception handling.
After converting to a list, type casting the values ​​to str and returning them using the int function.

반응형

댓글