본문으로 바로가기

LeetCode 2. Add Two Numbers

이 문제는 주어진 두 개의 Linked list를 사용해

주어진 조건에 따라 새로운 Linked list를 만들어 반환하는 프로그램을 짜라.

LeetCode에서 푼 문제 보기

LeetCode에서 문제 보기

github에서 코드 보기

문제 조건

문제 조건은 예시로 이해하는 편이 가장 좋다.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

0으로 시작하는 수는 나오지 않는다. (ex) (2 -> 4 -> 0)  X

문제 풀이

난 두 linked list를 각각 순회하여 수를 구한 다음, 더한 값을 뒤집어 Linked List로 표현하고 head를 반환하였다.

linked List의 처음부터 순서대로 1의 자리, 10의 자리,100의 자리 값이라는 점을 이용하였다.

(2 -> 4 -> 3) = 2*1 + 4 * 10 + 3 * 100 = 342

해당 Linked list가 어떤 수를 나타내는지를 구한 다음 두 수를 더한 값을 reversed 메소드를 이용하여 뒤집은 다음 각각의 문자를 Node에 넣어 Node끼리 서로 연결시켜주었다.

파이썬 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class Solution:
    """
    Runtime : faster than 39.31% of Python3
    Memory Usage : 13.5 MB, less than 5.21% of Python3
    """
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
 
        curn = l1
        num = 1
        first_number = 0
        while curn:
            first_number += curn.val * num
            curn = curn.next
            num *= 10
 
        curn = l2
        num = 1
        secound_number = 0
 
        while curn:
            secound_number += curn.val * num
            curn = curn.next
            num *= 10
 
        number = first_number + secound_number
 
        head = None
        for i in reversed(str(number)):
            print(i)
            if not head:
                head = ListNode(int(i))
                curn = head
            else:
                curn.next = ListNode(int(i))
                curn = curn.next
        return head
cs

#LeetCode 2 python #leetcode 파이썬 #LeetCode 2 Add Two Numbers  python