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

말하는 감자·2024년 12월 4일
1

LeetCode

목록 보기
24/32
post-thumbnail

1. 오늘의 학습 키워드

  • Linked List

2. 문제: 1290. Convert Binary Number in a Linked List to Integer

Description

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 representation of a number.

Return the decimal value of the number in the linked list.

The most significant bit is at the head of the linked list.

Example 1:

Input: head = [1,0,1]
Output: 5
Explanation: (101) in base 2 = (5) in base 10

Example 2:

Input: head = [0]
Output: 0

Constraints:

  • The Linked List is not empty.
  • Number of nodes will not exceed 30.
  • Each node's value is either 0 or 1.

3. 문제 풀이

오늘 문제는 매우 간단했기 때문에 문제를 이해하고 바로 코드를 구현하도록 하겠습니다.

주어진 연결 리스트는 0과 1로만 이뤄져있습니다. 주어진 연결리스트의 노드 값을 이진수로 판별하고 가져와서 정수형으로 반환하는 문제입니다.

연결 리스트를 순회하면서 노드 값을 저장해놓고 정수로 변환하면 해결될 것 같습니다. 그럼 입출력 상태만 확인해보도록 하겠습니다.

  • Input:
    • 0과 1로만 주어진 연결 리스트가 주어지는데 해당 연결리스트는 빈 리스트로는 주어지지 않는다고 합니다.
    • 30개를 넘어서지 않습니다.
  • Output:
    • int형 값을 반환합니다.

코드 구현

# Definition for singly-linked list.
class ListNode(object):
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next
class Solution(object):
    def getDecimalValue(self, head):
        # https://leetcode.com/problems/convert-binary-number-in-a-linked-list-to-integer/submissions/1469842705
        """
        :type head: Optional[ListNode]
        :rtype: int
        """
        ans = ''
        while head:
            ans += str(head.val)
            head = head.next
        return int(ans,2)

4. 마무리

이번 문제는 매우 간단했습니다. 실제 코테도 이런 문제만 나왔으면,,, ㅎㅎ

전체 코드는 다음 링크에서 확인할 수 있습니다.

읽어주셔서 감사합니다!

profile
할 수 있다

0개의 댓글