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.

Solution in Python
Approach 1: Elementary Math

# 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:
        result = ListNode(0)
        pre = result
        carry = 0

        while l1 or l2 or carry:
            value1 = l1.val if l1 else 0
            value2 = l2.val if l2 else 0
            current = value1 + value2 + carry
            if current >= 10:
                cur = ListNode(current-10)
                carry = 1
            else:
                cur = ListNode(current)
                carry = 0
            pre.next = cur
            pre = pre.next
            l1 = l1.next if l1 else None
            l2 = l2.next if l2 else None

        if (not l1) and (not l2) and carry:
            pre.next = ListNode(1)
        return result.next

Complexity Analysis

  • Time complexity: O(max(m, n)). Assume that m and n represents the length of l1 and l2 respectively, the algorithm above iterates at most max(m, n) times.
  • Space complexity: O(max(m, n)). The length of the new list is at most max(m, n) + 1.
最后修改日期: 2020年9月10日

留言

撰写回覆或留言

发布留言必须填写的电子邮件地址不会公开。