Leetcode 2. Add Two Numbers


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
  • のフル加算演算器の1つの形式と同様に、キャリー(加算ビット数)の解を利用する.
  •  

    学識


    論理回路を用いて
  • 計算機を計算する+/-演算を学習した.
  • Reference

  • コンピューターはどう計算しますか。
  • 本-Pythonアルゴリズムインタビュー