복's

[ LeetCode - 2 ] Add Two Numbers 본문

알고리즘/LeetCode

[ LeetCode - 2 ] Add Two Numbers

나복이 2023. 10. 30. 14:16
728x90

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

 

Add Two Numbers - LeetCode

Can you solve this real interview question? 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

leetcode.com

submissions 기록을 보면 올해 초 1월에 제출했다가 통과 못했던 기록들이 남아있다.

이 때까 알고리즘 처음으로 시작했던 때인데 LeetCode 처음으로 접하고 뭐가 뭔지 몰랐던 때인데 그 때는 Linked List 직접 구현하는건줄 알고 구현 하려고 시도 했던거로 기억한다....

 

사실 Linked List는 주어지고 이용만 하면 되는건데 ㅎㅎ..


[ 📌 풀이 ]

크게 거창한 것 없이 Linked List를 앞에서부터 순회하면 끝나는 문제이다.

다만 Linked List 특성항 Head를 기억해놓지 않으면(심지어 여기서 주어진 클래스는 Prev 가 없어서 뒤로 역방향 순회가 불가능하다.)

리스트 잃어버릴 수 있음

 

리스트를 순회하면서 String 값을 저장해 뒀다가 return 할 때 뒤집어서 주면 문제의 요구사항에 대응할 수 있게된다.


[ 📌 코드 - Python ]

"""
# Author    : Lee In Bok 
# Spend Time: 22m 55s
# Runtime   : 64 ms (Beats 61.49%)
# Memory    : 16.2 MB (Beats 94.25%)
# Algoritm  : Linked List
"""

# 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]:
        sums = list(str(self.reverse(l1) + self.reverse(l2)))
        head = ListNode()
        temp = head

        for idx, num in enumerate(sums[::-1]):
            temp.val = num
            
            if idx != len(sums) - 1:
                temp.next = ListNode()
                temp = temp.next

        return head

    def reverse(self, linked: Optional[ListNode]) -> int:
        temp = ""

        while linked:
            temp += str(linked.val)
            linked = linked.next

        return int(temp[::-1])

[ 📌 결과 ]

[ Result ]

728x90