[LeetCode] 2. Add Two Numbers

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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

Thought process:
Use a dummy node to start making the result list. Solve this problem just like solving an addition on paper:
  1. Iterate through both lists and pad the shorter list with 0 so that their lengths are equal.
  2. Iterate through both lists again and add numbers.
  3. If at the end carry = 1, add it to the end of result list.


Solution:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if (l1 == null) {
            return l2;
        }
        if (l2 == null) {
            return l1;
        }
        
        ListNode dummy = new ListNode(0);
        ListNode current = dummy;
        ListNode node1 = l1;
        ListNode node2 = l2;
        int carry = 0;
       
        while (node1.next != null || node2.next != null) {
            if (node1.next == null) {
                node1.next = new ListNode(0);
            } else if (node2.next == null) {
                node2.next = new ListNode(0);
            }
            node1 = node1.next;
            node2 = node2.next;
        }
        
        node1 = l1;
        node2 = l2;
        while (node1 != null && node2 != null) {
            int sum = node1.val + node2.val + carry;
            int digit = sum % 10;
            carry = sum / 10;
            current.next = new ListNode(digit);
            node1 = node1.next;
            node2 = node2.next;
            current = current.next;
        }
        
        if (carry > 0) {
            current.next = new ListNode(1);
        }
        
        return dummy.next;
    }
}

Time complexity: O(n).

Comments

Popular posts from this blog

[LeetCode] 714. Best Time to Buy and Sell Stock with Transaction Fee

[LeetCode] 269. Alien Dictionary

[LeetCode] 631. Design Excel Sum Formula