Wednesday, April 22, 2015

[LeetCode] Add Two Numbers

Add Two Numbers

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
Solution: The beauty of the following Java code lies in the little recursion at the end.

/**
 * 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 p = l1;
        ListNode q = l2;
        ListNode l = null;
        ListNode r = null;
        int flag = 0;
        while (p != null && q != null) {
            int sum = flag + p.val + q.val;
            flag = sum / 10;
            ListNode t = new ListNode(sum % 10);
            if (l == null) {
                l = t;
                r = t;
            } else {
                r.next = t;
                r = t;
            }
            p = p.next;
            q = q.next;
        }
        ListNode t = new ListNode(flag);
        if (p != null) {
            r.next = addTwoNumbers(p, t);
            return l;
        }        
        if (q != null) {
            r.next = addTwoNumbers(q, t);
            return l;
        }
        if (flag > 0) { 
            r.next = t;
        }
        return l;
    }
}

No comments:

Post a Comment