본문 바로가기

PS/릿코드

[릿코드 2] Add Two Numbers (파이썬/python)

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

 

링크드 리스트를 받아서 숫자를 추출해 더해준후
뒤집어서 제출하면 되는 문제
미디움은 아닌듯...?

class Solution:
    def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:

        str_l1 = ""
        str_l2 = ""

        while l1:
            str_l1 = str(l1.val) + str_l1
            l1 = l1.next

        while l2:
            str_l2 = str(l2.val) + str_l2
            l2 = l2.next

        result = str(int(str_l1) + int(str_l2))

        list_node = None
        result_node = None
        for re in reversed(result):
            if not result_node:
                result_node = ListNode(int(re))
                list_node = result_node
            else:
                list_node.next = ListNode(int(re))
                list_node = list_node.next

        return list_node
728x90