관리 메뉴

솜씨좋은장씨

[leetCode] 445. Add Two Numbers II (Python) 본문

Programming/코딩 1일 1문제

[leetCode] 445. Add Two Numbers II (Python)

솜씨좋은장씨 2020. 7. 27. 20:10
728x90
반응형

You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

 

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

 

Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.

 

Example:

Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 8 -> 0 -> 7

Solution

# 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: ListNode, l2: ListNode) -> ListNode:
        l1_list = []
        l2_list = []
        
        while l1.next != None:
            l1_list.append(str(l1.val))
            l1 = l1.next
        l1_list.append(str(l1.val))
        
        while l2.next != None:
            l2_list.append(str(l2.val))
            l2 = l2.next
        l2_list.append(str(l2.val))
        
        l1_num = int(''.join(l1_list))
        l2_num = int(''.join(l2_list))
        
        answer_num_str_list = list(str(l1_num + l2_num))
        
        answer = list(map(int, answer_num_str_list))
        
        for i in range(len(answer_num_str_list)):
            if i == 0:
                answerList = ListNode(answer_num_str_list[i])
            else:
                new_node = ListNode(answer_num_str_list[i])
                currNode = answerList
                while currNode.next != None:
                    currNode = currNode.next
                currNode.next = new_node
        
        return answerList

 

 

SOMJANG/CODINGTEST_PRACTICE

1일 1문제 since 2020.02.07. Contribute to SOMJANG/CODINGTEST_PRACTICE development by creating an account on GitHub.

github.com

 

Comments