2. Add Two Numbers Python3

Yelim Kim·2021년 9월 22일
0

Python Algorithm Interview

목록 보기
14/36
post-thumbnail

Problem

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 return the sum as a linked list.

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

Example 1:

Input: l1 = [2,4,3], l2 = [5,6,4]
Output: [7,0,8]
Explanation: 342 + 465 = 807.

Example 2:


Input: l1 = [0], l2 = [0]
Output: [0]

Example 3:

Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
Output: [8,9,9,9,0,0,0,1]
 

Constraints:


The number of nodes in each linked list is in the range [1, 100].
0 <= Node.val <= 9
It is guaranteed that the list represents a number that does not have leading zeros.

My code

# 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]:
        result = n = ListNode(0)
        up = 0
        while l1 or l2 or up:
            if l1:
                up += l1.val
                l1 = l1.next
            if l2:
                up += l2.val
                l2 = l2.next
            up, val = divmod(up, 10)
            n.next = n = ListNode(val)
            
        return result.next

Review

[실행 결과]
Runtime: 72 ms / Memory: 14.3 MB

[접근법]
l1과 l2의 맨 처음 요소의 합을 구한 후 10으로 나눈 나머지를 result에 저장하는 식이다.
만약 10으로 나눴을 때 몫이 생긴다면 다음 turn까지 가지고 가서 계산해준다.

[느낀점]
리스트를 스트링으로 바꾸고 뒤집어서 계산 후 다시 연결 리스트로 바꿔줄 방법을 생각해보긴 했는데... 훨씬 간단할 것 같기도 하고... 그치만 이런 연결 리스트로 풀라고 내논 문제에 양심에 찔렸기 때문에...(구구절절
result 리스트 하나만 가지고 했는데 자꾸 안되서 찾아보니 결과 리스트를 복제해서 한개 더 만들어줘야 했다. (초기화가 되기 때문)

profile
뜬금없지만 세계여행이 꿈입니다.

0개의 댓글