띠리링구 2024. 1. 20. 23:07

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

 

LeetCode - The World's Leading Online Programming Learning Platform

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

리트코드의 두 번째 문제이니 많은 사람들이 풀었을 것 같다.

두 개의 리스트에 각각 포인터를 두고 한칸씩 전진해가면서 새로운 리스트를 생성하면 된다.

크게 5가지 케이스가 있다.

1. 두 포인터 다 None이 아니다. (None이라는건 포인터가 리스트 끝까지 갔다는 뜻)

2. l1 포인터가 None이다

3. l2 포인터가 None이다.

4. 두 포인터 다 None인데 remaining이 남아있다. (remaining은 합을 10으로 나눈 몫으로, 다음 자릿수로 넘어가는 수를 뜻한다.)

5. 두 포인터 다 None이고 remaining도 없다 -> 이때 break하고 리턴하면된다.

 

 

# 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]:
        new_list = ListNode(0, None)
        lp, rp, np = l1, l2, new_list
        remaining = 0

        while True:
            if not lp and not rp and not remaining:
                break
            left_val = 0 if not lp else lp.val
            right_val = 0 if not rp else rp.val
            s = left_val + right_val + remaining
            cur_val = s % 10
            remaining = s // 10
            np.next = ListNode(cur_val)
            np = np.next
            lp = lp.next if lp else None
            rp = rp.next if rp else None

        return new_list.next