@@ -0,0 +1,2578 @@
+/*%0A * Key point: handle the carry especially when the length%0A *   of l1 and l2 are different and need an extra bit to%0A *   store a carry%0A */%0A%0A/**%0A * Definition for singly-linked list.%0A * public class ListNode %7B%0A *     int val;%0A *     ListNode next;%0A *     ListNode(int x) %7B%0A *         val = x;%0A *         next = null;%0A *     %7D%0A * %7D%0A */%0Apublic class Solution %7B%0A    public ListNode addTwoNumbers(ListNode l1, ListNode l2) %7B%0A        if(l1 == null && l2 == null)%0A            return null;%0A        else if(l1 == null && l2 != null)%0A            return l2;%0A        else if(l1 != null && l2 == null)%0A            return l1;%0A            %0A        ListNode result = null;%0A        ListNode runner = null;%0A        %0A        int carry = 0;%0A        int digitValue = 0;%0A        int tempSum = 0;%0A        boolean firstDigit = true;%0A        %0A        //handle the common part of l1 and l2%0A        while(l1 != null && l2 != null)%7B%0A            tempSum = carry + l1.val + l2.val;%0A            carry = tempSum / 10;%0A            digitValue = tempSum %25 10;%0A%0A            //first digit%0A            if(firstDigit == true)%7B%0A                runner = new ListNode(digitValue);%0A                result = runner;%0A                firstDigit = false;%0A            %7D%0A            else%7B%0A                runner.next = new ListNode(digitValue);%0A                runner = runner.next;%0A            %7D%0A                %0A            l1 = l1.next;%0A            l2 = l2.next;%0A        %7D%0A        %0A        //if l1 and l2 are of same length%0A        if(l1 == null && l2 == null)%7B%0A            if(carry == 0)%0A                return result;%0A            else%7B%0A                runner.next = new ListNode(carry);%0A                return result;%0A            %7D%0A        %7D%0A        %0A        //swap, to make sure l1 is longer than l2%0A        if(l1 == null)%7B%0A            ListNode temp = l1;%0A            l1 = l2;%0A            l2 = temp;%0A        %7D%0A        %0A        if(l2 == null)%7B%0A%0A            //link the remain part of l1 to the tail of result%0A            runner.next = l1;%0A            %0A            //if when l2 ends, carry is not 0%0A            while(carry != 0)%7B%0A                tempSum = carry + l1.val;%0A                l1.val = tempSum %25 10;%0A                carry = tempSum / 10;%0A                %0A                if(l1.next != null)%7B%0A                    l1 = l1.next;%0A                %7D%0A                else%7B//reach the end of l1%0A                    if(carry != 0)%0A                        l1.next = new ListNode(carry);%0A                    carry = 0;%0A                %7D%0A                %0A            %7D%0A        %7D%0A            %0A        return result;%0A%0A    %7D%0A%7D

Add Two Numbers