소프트웨어에 대한 모든 것

LeetCode 풀기 - 2. Add Two Numbers 본문

알고리즘/LeetCode

LeetCode 풀기 - 2. Add Two Numbers

앤테바 2022. 3. 11. 06:33
반응형

2. Add Two Numbers

https://leetcode.com/problems/add-two-numbers/

 

Add Two Numbers - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

문제)

솔루션1) bruto-force

풀이 순서:

1) 리스트를 array 자료구조로 변환

2) carry를 계산하면서 각 자리수 add

3) 최종 결과물 array를 리스트로 변환해서 리턴

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:        
        # 리스트노드를 array 자료구조로 변환
        def trans_to_arr(head):
            nums = []
            while head:
                nums.append(head.val)
                head = head.next
            return nums
        
        # array를 리스트노드로 변환
        def trans_to_list(nums):
            dummy = cur = ListNode(0)
            for n in nums:
                cur.next = ListNode(n)
                cur = cur.next
            return dummy.next
        
        nums1 = trans_to_arr(l1)
        nums2 = trans_to_arr(l2)
        
        # 두 수 더하기 연산
        res = []
        carry = 0
        for n1, n2 in zip_longest(nums1, nums2, fillvalue=0):
            carry, remainder = divmod(n1+n2+carry, 10)
            res.append(remainder)
        if carry == 1:
            res.append(1)
            
        return trans_to_list(res)

솔루션2)

솔루션1을 더 심플하게 개선한 버전입니다.

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:        
        dummy = cur = ListNode(0)
        carry = 0
        while l1 or l2 or carry:
            cur.next = ListNode()
            cur = cur.next
            n1, n2 = 0, 0
            if l1:
                n1 = l1.val
                l1 = l1.next
            if l2:
                n2 = l2.val
                l2 = l2.next
                
            carry, remainder = divmod(n1 + n2 + carry, 10)
            cur.val = remainder
        return dummy.next
반응형
Comments