본문 바로가기
🖥️ 문제 풀이/리트코드(Leetcode)

[LeetCode 해석 및 풀이] 2. Add Two Numbers

by 뒬탕 2024. 4. 20.
반응형

LeetCode 문제 해석 및 풀이 방법

 

문제 2. 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.

 

한글

두 음수가 아닌 정수를 나타내고 있는 두 개의 비어있지 않은 연결 리스트가 주어집니다. 숫자들은 역순으로 넣어져있으며, 각 노드들은 한 자리수를 나타냅니다. 두 수를 더하고 그 합을 연결 리스트로 반환하시오.

 

숫자 0을 제외하고는 첫 자리수가 0이 아님을 가정할 수 있습니다.

 

제한조건

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

 

입출력 예

입력 출력
l1 = [2,4,3], l2 = [5,6,4] [7,0,8]
l1 = [0], l2 = [0] [0]
l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9] [8,9,9,9,0,0,0,1]

 

 

해답 및 해설

파이썬 (Python)

class Solution:
    def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
        dummy_answer_head = now_node = ListNode()
        round_up = 0

        while l1 or l2 or round_up:
            calculate = 0
            if l1:
                calculate += l1.val
                l1 = l1.next
            if l2:
                calculate += l2.val
                l2 = l2.next
            if round_up:
                calculate += round_up
                round_up = 0
            
            if calculate >= 10:
                round_up = 1
                calculate %= 10
            
            now_node.next = ListNode(calculate)
            now_node = now_node.next
        
        return dummy_answer_head.next

if를 통해 값이 있을 때만 신경써준다는게 핵심

반응형

댓글