LeetCode problem solving note 1 -- sum of two numbers

In this paper, two non empty linked lists are given to represent two non negative integers. Their respective digits are stored in reverse order, and each node can only store one digit.

If we add the two numbers together, we will return a new linked list to represent their sum.

You can assume that neither of these numbers starts with 0 except the number 0.

Example:

Input: (2 - > 4 - > 3) + (5 - > 6 - > 4)
Output: 7 - > 0 - > 8
 Reason: 342 + 465 = 807

solution

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if(l1==null && l2 == null){
            return null;
        }
        if(l1==null){ //The two input lengths may be different. Fill 0 for the blank
            l1 = new ListNode(0);
        }else if(l2==null){
            l2 = new ListNode(0);
        }
        int x = l1.val +l2.val;
        int y = 0; //Enter digit
        if(x >= 10){
            x = x - 10;
            y = 1;
        }
        ListNode node = new ListNode(x);
        ListNode nodeNext = addTwoNumbers(l1.next, l2.next);
        node.next = nodeNext;
        if(y > 0){ //If there is carry, add 1 to the higher one in turn until there is no carry
            if(node.next == null){
                node.next = new ListNode(y);
            }else{
                node.next.val = node.next.val + y;
                ListNode t = node.next;
                while(t.val==10){
                    t.val = 0;
                    if(t.next!=null){
                        t = t.next;
                        t.val = t.val + 1;
                    }else{
                        t.next = new ListNode(1);
                    }
                }
            }
        }
        return node;
    }
}

 

Posted by pilau on Sat, 07 Dec 2019 19:58:50 -0800