Algorithm/파이썬 알고리즘 인터뷰 스터디

[연결리스트] 16 두 수의 덧셈(Reverse Linked List)

supremo7 2021. 8. 9. 20:14

<LeetCode 문제>

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

 

Add Two Numbers - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

역순으로 저장된 연결 리스트의 숫자를 더하는 문제입니다.

<풀이>

연결리스트의 값들을 문자열로 이어붙이고 숫자로 변환한 다음 계산한 결과를 다시 연결리스트로 바꾸면 됩니다.

# 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]:
        n1_str="" #l1의 숫자들 연결
        n2_str="" #l2의 숫자들 연결
        while l1!= None:
            n1_str += str(l1.val)
            l1 = l1.next
        while l2!= None:
            n2_str += str(l2.val)
            l2 = l2.next
        
        result = int(''.join(reversed(n1_str))) + int(''.join(reversed(n2_str))) #int로 덧셈계산
        
        #파이썬 리스트를 연결 리스트로 변환
        prev = None
        for s in str(result):
            node = ListNode(int(s))
            node.next=prev
            prev=node
        return node

 

추가로 전가산기(full adder)를 구현하여 문제를 해결할 수도 있습니다.

<학습내용>

1.

<학습이 필요한 내용>

1.