작심삼일

[LeetCode] 2 | Add Two Numbers | Python 본문

스터디/코테

[LeetCode] 2 | Add Two Numbers | Python

yun_s 2022. 3. 10. 10:36
728x90
반응형

문제 링크: https://leetcode.com/problems/add-two-numbers/


문제

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.


조건

  • 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.

내 풀이

리스트의 맨 앞에부터 일의 자리이므로 차례로 더하면 된다.

어릴 때 했던 것처럼 각 자리수의 합이 10이 넘을 때 올림에 주의해야한다.

그리고 마지막에 3+8=11처럼 한 자리가 증가할 수도 있기 때문에 그 부분도 확인해야한다.


코드

# 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]:
        ten = 0
        ans = ListNode()
        if l1 and l2:
            sums = l1.val + l2.val
            sums, ten = self.is_bigger_than_10(sums)
            ans.next = ListNode(sums)
        elif l1:
            ans.next = ListNode(l1.val)
        elif l2:
            ans.next = ListNode(l2.val)
        else:
            return ListNode()
        head = ans.next
        
        while l1.next or l2.next:
            if l1.next and l2.next:
                l1, l2 = l1.next, l2.next
                sums = l1.val + l2.val + ten
                sums, ten = self.is_bigger_than_10(sums)
                head.next = ListNode(sums)
            elif l1.next:
                l1 = l1.next
                sums, ten = self.is_bigger_than_10(l1.val + ten)
                head.next = ListNode(sums)
            elif l2.next:
                l2 = l2.next
                sums, ten = self.is_bigger_than_10(l2.val + ten)
                head.next = ListNode(sums)
            head = head.next
        
        if ten: head.next = ListNode(1)
        
        return ans.next
    
    def is_bigger_than_10(self, sums):
        if sums > 9:
            ten = 1
            sums -= 10
        else:
            ten = 0
        return sums, ten
728x90
반응형
Comments