본문 바로가기
LeetCode/Problems

LeetCode 2. Add Two Numbers [Linked List]

by 벤진[Benzene] 2020. 6. 9.

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 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.

 

Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)

Output: 7 -> 0 -> 8

Explanation: 342 + 465 = 807.

 

-Summary-

1. Create two dummy list nodes to update and return the answer.

2. Loop through until there is a value in l1 or l2 or any carryover number.

3. Inside the loop, for each digit from the l1 and l2, we add l1 and l2 then add it to the Curr ListNode (%10 if summation over 10 and add to the CarryOver).

4. Keep update and move the Curr LinkedList

5. return res

 

-Similar Solution-

Using divmod function for Remainder and Quotient

# 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:
        head = root = ListNode
        
        carry = 0
        
        while l1 or l2 or carry:
            sumNode = 0
            if l1:
                sumNode += l1.val
                l1 = l1.next
            if l2:
                sumNode += l2.val
                l2 = l2.next
                
            carry, val = divmod(sumNode+carry,10)
            root.next = ListNode(val)
            root = root.next
            
        return head.next

 

모든 문제에 대한 저작권은 LeetCode 회사에 있습니다. [Copyright © 2020 LeetCode]

댓글