LeetCode (6) - Add Two Numbers (파이썬, python)

1 분 소요

❓ 문제

  • You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.

    You may assume the two numbers do not contain any leading zero, except the number 0 itself.

    Example 1:

    img

    Input: l1 = [2,4,3], l2 = [5,6,4]
    Output: [7,0,8]
    Explanation: 342 + 465 = 807.
    

    Example 2:

    Input: l1 = [0], l2 = [0]
    Output: [0]
    

    Example 3:

    Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
    Output: [8,9,9,9,0,0,0,1]
    

    Constraints:

    • The number of nodes in each linked list is in the range [1, 100].
    • 0 <= Node.val <= 9
    • It is guaranteed that the list represents a number that does not have leading zeros.

Given Code

# 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]:
        
  
            

내 풀이

풀긴 했는데 딴거하면서 하느라 더럽게 풀었다. 더러운 이유는 결과를 뒤집기 위해 while문을 두개 두었고 (순서 뒤집을라고) 에러케이스 (한자리수 덧셈 등등) 대비한 코드를 굳이 따로 두었어야했나 싶다.

# 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, l2):
        # if l1.next == None and l2.next == None:
        #     return ListNode(l1.val + l2.val, None)
        l3 = None

        ad = 0
        while (l1 != None or l2 != None):
            if l1 == None:
                l1 = ListNode(0, None)
            if l2 == None:
                l2 = ListNode(0, None)
            tmp = ad + l1.val + l2.val
            if tmp > 9:
                ad = 1
                tmp -= 10
            else:
                ad = 0
            # print(tmp, l1, l2, l3)
            l3 = ListNode(tmp, l3)
            # print(l3)
            # print(l1, l2)

            l1 = l1.next
            l2 = l2.next

        if ad == 1:
            l3 = ListNode(1, l3)

        if l3 == None:
            res = ListNode()
        else:
            res = None
        # print(l3)

        while (l3 != None):
            res = ListNode(l3.val, res)
            l3 = l3.next


        return res