[leetcode] 2. Add Two Numbers

2021. 8. 3. 18:15노트/Algorithm : 알고리즘

 

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.
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next


def MakeInt(ListNode):
    c , num = 0, 0
    while ListNode:
        v = ListNode.val 
        ListNode = ListNode.next 
        num += v * pow(10, c)
        c += 1 
    return num

def MakeLinkedList(num): # 807
    head = ListNode(None)
    node = head
    while True:
        v = num % 10 # 7 
        one = ListNode(v)
        node.next = one
        node = one
        num = num // 10 # 80 
        
        if num == 0:
            break
    return head.next

 
class Solution:
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        num1 , num2 = MakeInt(l1) , MakeInt(l2)
        num3 = num1 + num2 
        solution = MakeLinkedList(num3)
        print(solution)
        return solution

 

* 연결 리스트 팁 

head 는 None 값을 지정한다 (초기값) 

node는 기준이다. 포인터라고 생각하자. 

node의 next가 뭐인지 연결하자.

그다음에 node를 기준으로 바꾸자. 

연결리스트의 첫번째 값이 일의자리수가 되도록 편하게 문제를 준거다. 

 

% 나머지 

// 몫 

 

cf . 54321 숫자에서 5,4,3,2,1 각각 출력하기 

num % 10  -> 1 

num = num // 10 -> 5432 

num % 10 -> 2 

num = num // 10 -> 543 

num % 10 -> 3 

num = num // 10 -> 54 

num % 10 -> 4 

num = num // 10 -> 5

num % 10 -> 5 

num = num // 10 -> 0