Saturday, February 16, 2013

[LeetCode] Add Two Numbers

Thoughts: 
    Use a easy tail recursion taking the carry bit into consideration.

Code:
public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        return add(l1, l2, 0);
    }
    public ListNode add(ListNode l1, ListNode l2, int carry){
        ListNode result = null;
        int temp = 0;
        if( l1 != null && l2 != null){
            int val = l1.val + l2.val + carry;
            result = new ListNode(val%10);
            temp = val > 9? 1: 0;
            result.next = add(l1.next, l2.next, temp);
        }else if( l1 == null && l2 != null){           
            int val = l2.val + carry;
            result = new ListNode(val%10);
            temp = val > 9? 1: 0;
            result.next = add(null, l2.next, temp);
        }else if( l1 != null && l2 == null){
            int val = l1.val + carry;
            result = new ListNode(val%10);
            temp = val > 9? 1: 0;
            result.next = add(l1.next, null, temp);
        }else{
            if( carry == 1 ){
                result = new ListNode(carry);
            }
        }
        return result;
    }
}

No comments:

Post a Comment