欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

2 add two numbers

程序员文章站 2024-03-17 21:56:58
...

title: Add Two Numbers
tags:
- add-two-numbers
- No.2
- medium
- list
- naive


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

Corner Cases

  • at least one empty
input:  [], []
return: []

input:  [9], []
return: [9]
  • carry with different lengths
input:  [9, 9], [9, 9, 9, 9, 9]
output: [1, 0, 0, 0, 0, 9, 8]

Solution

Naive

Pay attention to:

  1. Carry. One more node may occur.
  2. Initialization.
  3. Numbers with different sizes.

Running time: O(n).

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    Solution () {}

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        // O(n)

        ListNode p1 = l1;
        ListNode p2 = l2;
        ListNode h  = null;
        ListNode p  = h;

        // initialization
        int pval  = 0;
        int carry = 0;

        boolean e1  = true;
        boolean e2  = true;

        // O(n)
        // `x==null` for input:
        // `l1==null` and `l2==null`
        while (p1 != null || p2 != null) {
            // check if p1 and p2 ends
            e1 = e1 && (p1 != null);
            e2 = e2 && (p2 != null);

            // update p1, p2
            // calculate value
            if (e1 && e2) {
                pval = p1.val + p2.val + carry;
                p1   = p1.next;
                p2   = p2.next;
            }
            else if (e1 && !e2) {
                pval = p1.val + carry;
                p1   = p1.next;
            }
            else if (!e1 && e2) {
                pval = p2.val + carry;
                p2   = p2.next;
            }
            else { /* which is impossible */ }

            // update value
            carry = (pval > 9) ? 1 : 0;
            pval  = pval - carry * 10;

            // update p
            if (p == null) {
                h = new ListNode(pval);
                p = h;
            }
            else {
                p.next = new ListNode(pval);
                p      = p.next;
            }
        }

        if (carry == 1) {
            p.next = new ListNode(1);
        }

        return h;
    }
}

If in natural order

Input:  [3, 4, 2]
        [5, 6, 4]
Return: [8, 0, 7]

It's impossible to know the highest bit without traversing the whole list. Thus O(n) time of pre-processing is necessary. We can reverse the list first.

For list reversing, we set 3 pointers:a, b, c:

  1. initialization a, b = null; c = head;
[a,b]  [c] -> [x] -> [x] -> [x]
  1. the list has been reversed in i steps, and there is a hole between pointer b and c.
[x] <- [a] <- [b]  [c] -> [x] -> [x]

The original list is broken into 2 lists, with b and c as their heads independently.

  1. a = b
[x] <- [x] <- [a,b]  [c] -> [x] -> [x]
  1. b = c
[x] <- [x] <- [a]  [b,c] -> [x] -> [x]
  1. c = c.next now the two heads are a and b.
[x] <- [x] <- [a]  [b] -> [c] -> [x]
  1. b.next = a reverse the pointer of b and then we return to state [1].
[x] <- [x] <- [a] <- [b]  [c] -> [x]
  1. finalization c == null; return b;
[x] <- [x] <- [a] <- [b]  [c]

Then the rest of the algorithm is generally same with the reversed one. Note that we change the node pointing backwards to get a natural result:

1. [y]      [p,x] -> [x] -> [x]
2. [y]   -> [p,x] -> [x] -> [x]
3. [p,y] -> [x]   -> [x] -> [x]

Running time is still O(n), with more loops:

class Solution {
    Solution () {}

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        // O(n)
        ListNode r1 = reverse(l1);
        ListNode r2 = reverse(l2);

        ListNode p1 = r1;
        ListNode p2 = r2;

        if (p1 == null && p2 == null) {return null;}

        // initialization
        int pval  = p1.val + p2.val;
        int carry = (pval > 9) ? 1 : 0;
        pval      = pval - carry * 10;

        ListNode p  = new ListNode(pval);
        p1 = p1.next;
        p2 = p2.next;

        boolean e1  = true;
        boolean e2  = true;

        // O(n)
        while (p1 != null || p2 != null) {
            // check if p1 and p2 ends
            e1 = e1 && (p1 != null);
            e2 = e2 && (p2 != null);

            // update p1, p2
            // calculate value
            if (e1 && e2) {
                pval = p1.val + p2.val + carry;
                p1   = p1.next;
                p2   = p2.next;
            }
            else if (e1 && !e2) {
                pval = p1.val + carry;
                p1   = p1.next;
            }
            else if (!e1 && e2) {
                pval = p2.val + carry;
                p2   = p2.next;
            }
            else { /* which is impossible*/ }

            // update value
            carry = (pval > 9) ? 1 : 0;
            pval  = pval - carry * 10;

            // update node
            ListNode np = new ListNode(pval);
            np.next = p;
            p       = np;
        }

        if (carry == 1) {
            ListNode np = new ListNode(1);
            np.next = p;
            p       = np;
        }

        return p;
    }

    public ListNode reverse(ListNode l) {
        ListNode a = null;
        ListNode b = null;
        ListNode c = l;

        while (c != null) {
            a      = b;
            b      = c;
            c      = c.next;
            b.next = a;
        }

        return b;
    }
}

转载于:https://www.jianshu.com/p/eae89e662450