[LeetCode] 2. Add Two Numbers

/**
 * 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) {
        /***
         * Image: 1->null; 9 -> 9 -> 9 -> null  =======> 1 .> (0) .> (0) -> null; 9 -> 9 -> 9 -> null 
         * Key: 1) The two list might not be same length, the one that is shorter could be consider as 0 on that digit
         *      2) Must be careful with the carry, [1], [9,9] will move twice
         *      3) The length of two lists could be very different, eg.[1], [1,2,3,4,5], has to make sure the longer list 
         *         has been move till the end, could not just check one level after the short node is null.
         * Trick 1) How to write a for loop 
         *       2) % for digit
         *       3) / for carry
         *       4) when list = null, could not use list.next = s; ==> nullPointerException
         *
        ***/
        ListNode current = new ListNode(0); // create a dumny node
        ListNode head = current; //to remember the start node
        int carry = 0;
        for(;
            l1 != null || l2 != null || carry > 0;
            l1 = (l1 == null)? null : l1.next, 
            l2 = (l2 == null)? null : l2.next){
                int v1 = (l1 == null)? 0 : l1.val; // if it is null, use 0, it won't affect result
                int v2 = (l2 == null)? 0 : l2.val;
                int sum = v1 + v2 + carry;
                ListNode s = new ListNode(sum % 10);
                carry = sum / 10; // int / int equal to int 
                current.next = s;
                current = s;
            }
        return head.next;
    }
}

 ToDo: Need to check how to write the reversed one cc150

posted on 2015-12-09 14:10  codingEskimo  阅读(156)  评论(0编辑  收藏  举报

导航