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:
30
.0
or 1
.오늘 문제는 매우 간단했기 때문에 문제를 이해하고 바로 코드를 구현하도록 하겠습니다.
주어진 연결 리스트는 0과 1로만 이뤄져있습니다. 주어진 연결리스트의 노드 값을 이진수로 판별하고 가져와서 정수형으로 반환하는 문제입니다.
연결 리스트를 순회하면서 노드 값을 저장해놓고 정수로 변환하면 해결될 것 같습니다. 그럼 입출력 상태만 확인해보도록 하겠습니다.
# 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)
이번 문제는 매우 간단했습니다. 실제 코테도 이런 문제만 나왔으면,,, ㅎㅎ
전체 코드는 다음 링크에서 확인할 수 있습니다.
읽어주셔서 감사합니다!