Leetcode 2. Add Two Numbers

Daehwi Kim·2021년 6월 28일
0

LeetCode

목록 보기
20/23

2. Add Two Numbers

Medium


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.

 

풀이

1. LinkedList -> Python 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: ListNode, l2: ListNode) -> ListNode:
        
        # LinkedList를 List로 만들기위한 변수설정
        result = ''
        l1_st = ''
        l2_st = ''
    
    	# l1과 l2 링크드 리스트 스트링화
        while l1 or l2:
            if l1:
                l1_st = str(l1.val) + l1_st
                l1 = l1.next
            if l2:
                l2_st = str(l2.val) + l2_st
                l2 = l2.next
        # 결과값 Python 리스트화
        result = list(str(int(l1_st)+int(l2_st)))
        
        # 역순 LinkedList head
        l = ListNode(result.pop())
        
        # LinkedList Pointer
        temp = l
        
        # Python List -> LinkedList
        # 맨뒤의 값 추출 -> Time Complexity O(1)
        while result:
            temp.next = ListNode(result.pop())
            temp = temp.next
            
        return l
  • Python 리스트를 -> String -> LinkedList로 변환하여 풀이하였다.

  • 역순으로 링크드리스트를 만드는 것은 Python리스트의 맨뒤값 추출(O(1))의 시간복잡도로 전체 O(n)의 시간복잡도이다.


2. 전가산기를 이용한 풀이

# 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:
        # root 노드
        root = head = ListNode(None)
        
        # 자리올림수
        carry = 0
        
        # 전가산기 과정
        while l1 or l2 or carry:
            sum = 0
            if l1:
                sum += l1.val
                l1 = l1.next
            if l2:
                sum += l2.val
                l2 = l2.next
            
            # 몫과 나머지
            carry, val = divmod(carry+sum, 10)
            head.next = ListNode(val)
            head = head.next
        return root.next
  • 전가산기의 유사한 형태로 carry(자리 올림수)를 이용한 풀이이다.

 

배운점

  • 컴퓨터의 +/- 연산을 가산기와 전가산기를 논리회로를 이용하여 계산한다는 점을 배웠다.

Reference

profile
게으른 개발자

0개의 댓글