LeetCode Problem 2: Add Two Numbers

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

Approach: Elementary Math
Algorithm

Just like how you would sum two numbers on a piece of paper. We begin by summing the least-significant digits, which is the head of l 1 l1 l1 and l 2 l2 l2. Since each digit is in the range of 0…9, summing two digits may “overflow”. For example, 5 + 7 = 12. In this case, we set the current digit to 2 and bring over the c a r r y = 1 carry = 1 carry=1 to the next iteration. c a r r y carry carry must be either 0 or 1 because the largest possible sum of two digits (including the carry) is 9 + 9 + 1 = 19.

The pseudocodes are as follows:

  • Initialize current node to dummy head of the returning list.
  • Initialize carry to 0.
  • Loop through lists l 1 l1 l1 and l 2 l2 l2 until you reach both ends.
    • Update c a r r y carry carry = c a r r y carry carry + p ′ s p's ps value. If p p p has reached the end of l 1 l1 l1, set to 0.
    • Advance p p p.
    • Update c a r r y carry carry = c a r r y carry carry + q ′ s q's qs value. If q q q has reached the end of l 2 l2 l2, set to 0.
    • Advance q q q.
    • Create a new node with the digit value of ( c a r r y carry carry m o d mod mod 10 10 10) and set it to current node’s next, then advance current node to next.
    • Update c a r r y = c a r r y / 10 carry = carry / 10 carry=carry/10.
  • Check if c a r r y = 1 carry = 1 carry=1. If so, append a new node with digit 1 to the returning list.
  • Return dummy head’s next node.

Note that we use a dummy head to simplify the code. Without a dummy head, you would have to write extra conditional statements to initialize the head’s value.

Take extra caution of the following cases:

Test caseExplanation
l 1 = [ 0 , 1 ] l1 = [0 ,1] l1=[0,1]
l 2 = [ 0 , 1 , 2 ] l2 = [0, 1, 2] l2=[0,1,2]
When one list is longer than the other.
l 1 = [ ] l1 = [] l1=[]
l 2 = [ 0 , 1 ] l2 = [0, 1] l2=[0,1]
When one list is null, which means an empty list.
l 1 = [ 9 , 9 ] l1 = [9, 9] l1=[9,9]
l 2 = [ 1 ] l2 = [1] l2=[1]
The sum could have an extra carry (1) at the end, which is easy to forget.
Code: C++
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode *dummyHead = new ListNode(0);
        ListNode *p = l1, *q = l2, *curr = dummyHead;
        int carry = 0;
        while (p != NULL || q != NULL)
        {
            if (p != NULL)
            {
                carry += p -> val;
	            p = p -> next;
            }
            if (q != NULL)
            {
                carry += q -> val;
	            q = q -> next;
            }
            ListNode *next1 = new ListNode(carry % 10);
            carry /= 10;
            curr -> next = next1;
            curr = curr -> next;
        }
        if (carry > 0)
        {
            ListNode *next2 = new ListNode(carry);
            curr -> next = next2;
        }
        return dummyHead -> next;
    }
};

Complexity Analysis
  • Time complexity: O ( m a x ( m , n ) ) O(max(m, n)) O(max(m,n)). Assuming that m m m and n n n represents the length of l 1 l1 l1 and l 2 l2 l2 respectively, the algorithm above iterates at most m a x ( m , n ) max(m, n) max(m,n) times.

  • Space complexity: O ( m a x ( m , n ) ) O(max(m, n)) O(max(m,n)). The length of the new list is at most m a x ( m , n ) + 1 max(m, n) + 1 max(m,n)+1.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值