Add Two Numbers

Problem Id: 2 Difficulty: Medium Tag: Linked List Tag: Math


Intuition

The diffcult part of this problem is to handle carefully about the linked list.

Solution


# Definition for singly-linked list.
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None


class Solution:
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        head = ListNode(None)
        current = head
        exceed = 0
        while l1 or l2 or exceed:
            if l1 is None:
                a = 0
            else:
                a = l1.val
                l1 = l1.next
            if l2 is None:
                b = 0
            else:
                b = l2.val
                l2 = l2.next
            current.next = ListNode((a + b + exceed) % 10)
            current = current.next
            exceed = (a + b + exceed) // 10
        return head.next