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 the sum as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Examples

Example 1:

(2 -> 4 -> 3) + (5 -> 6 -> 4) => 7 -> 0 -> 8

Input: l1 = [2,4,3], l2 = [5,6,4]
Output: [7,0,8]

Explanation:  342 + 465 = 807

Solution

This problem is straight forward, but consider the cases:

  • We should not forget the carry, especially when we have one more digit just for the carry. (e.g., 5 + 7 = 12, the ’1′ in 12 is due to the carry from last digit)
  • Two numbers might not have same number of digits. (e.g., 1 + 123 are one digit and three digit numbers)
  • As the link list are reversed that of number, we have taken care of adding it from right to left i.e. least significant digit to most significant digit.

Method 1 - OR in While Loop

public ListNode addTwoNumbers(ListNode l1, ListNode l2) {  
    int carry = 0;  
  
    ListNode newHead = new ListNode(0);  
    ListNode l3 = newHead;  
  
    while (l1 != null || l2 != null) {  
        if (l1 != null) {  
            carry += l1.val;  
            l1 = l1.next;  
        }  
  
        if (l2 != null) {  
            carry += l2.val;  
            l2 = l2.next;  
        }  
  
        l3.next = new ListNode(carry % 10);  
        l3 = l3.next;  
        carry /= 10;  
    }  
	// important edge case
    if (carry > 0) {  
        l3.next = new ListNode(carry);  
    }  
  
    return newHead.next;  
}

Note that we are calling - if (p1!=null) and if(p2!=null) - we can optimize a little, but code is not that clean.

Method 2 - And in While Loop

public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
	ListNode dummy = new ListNode(-1);
	ListNode dummyHead = dummy;
	int extra = 0;
	while (l1 != null && l2 != null) {
		dummy.next = new ListNode((l1.val + l2.val + extra) % 10);
		extra = l1.val + l2.val + extra > 9 ? 1 : 0;
		dummy = dummy.next;
		l1 = l1.next;
		l2 = l2.next;
	}
	ListNode n = l1 != null ? l1 : l2;
	while (n != null) {
		dummy.next = new ListNode((n.val + extra) % 10);
		extra = n.val + extra > 9 ? 1 : 0;
		n = n.next;
		dummy = dummy.next;
	}
	if (extra == 1) {
		dummy.next = new ListNode(1);
	}
	return dummyHead.next;
}