Add Two Numbers(Medium)

You are given two linked lists representing two non-negative numbers. 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.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)

Output: 7 -> 0 -> 8

Java代码

public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    if (l1 == null)
        return l2;
    if (l2 == null)
        return l1;

    ListNode head = new ListNode(0), r = head, p = l1, q = l2, tmp;
    r.next = null;
    int carry = 0, sum;

    while (p != null || q != null) {
        sum = 0;
        sum += carry;
        if (p != null) {
            sum += p.val;
            p = p.next;
        }
        if (q != null) {
            sum += q.val;
            q = q.next;
        }
        tmp = new ListNode(sum % 10);
        carry = sum / 10;
        r.next = tmp;
        r = r.next;
    }

    if (carry == 1) {
        tmp = new ListNode(1);
        r.next = tmp;
        r = r.next;
    }
    r.next = null;

    return head.next;
}

Add Two Numbers II (0445/Medium)

You are given two linked lists representing two non-negative numbers. The most significant digit comes first 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.

Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.

Example:

Input: (7 ->2 ->4 ->3) + (5 -> 6 ->4)
Output: 7 ->8 ->0 ->7

可看成是

Add Two NumbersReverse Linked List

的综合. 先reverse在逐个add, 最后把结果reverse回来.

results matching ""

    No results matching ""