Add two numbers

Given two non-empty lists representing non-negative integers. Numbers are stored in reverse order and their nodes contain only one number. Adds two numbers and returns them as a linked list.

Example

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

Solution

Use a variable to keep track of the carry and start at the head of the list to simulate the number of bits and totals with the least significant digit.

Just like you add two numbers on a piece of paper, we add the least significant digit first, which is the head of L1 and L2. Since each digit is in the range 0...9, adding two digits may "overflow". For example 5 + 7 = 12. In this case, we set the current number to 2 and pass carry=1 to the next iteration. The carry must be either 0 or 1, because the largest possible sum of two digits (including the carry) is 9 + 9 + 1 = 19.

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) {
        int x = (p != null) ? p.val : 0;
        int y = (q != null) ? q.val : 0;
        int sum = carry + x + y;
        carry = sum / 10;
        curr.next = new ListNode(sum % 10);
        curr = curr.next;
        if (p != null) p = p.next;
        if (q != null) q = q.next;
    }
    if (carry > 0) {
        curr.next = new ListNode(carry);
    }
    return dummyHead.next;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326449025&siteId=291194637