The topic of dry

You are given two non-empty linked lists representing two non-negative integers. Each digit is stored in reverse order, and only one digit can be stored per node.

You add the two numbers and return a linked list representing the sum in the same form.

You can assume that neither of these numbers will start with 0, except for the number 0.

Example 1:

Input: l1 = [2, 3], l2 =,6,4 [5] output:,0,8 [7] : 342 + 465 = 807.Copy the code

Example 2:

Input: L1 = [0], L2 = [0] Output: [0]Copy the code

Solution: Iteration

And it’s actually pretty easy to do is we start adding up, round up when we’re greater than 10 and record the ten digits that are greater than 10 for the next addition.

One of the things to note is that we are creating a new linked list for calculation.

Code implementation:

Execution time: 120 ms, beating 98.32% of all JavaScript commits

Memory consumption: 43 MB, beating 54.09% of all JavaScript commits

/ * * *@param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}* /
var addTwoNumbers = function (l1, l2) {
    let newlist = new ListNode(0);
    let nextyu = 0;
    let zhi = 0;
    let current = newlist
    while(l1 ! =null&& l2 ! =null) {
        zhi = (l1.val + l2.val+nextyu) % 10;
        current.next = new ListNode(zhi)
        nextyu = Math.floor((l1.val + l2.val+nextyu) / 10);
        l1 = l1.next;
        l2 = l2.next;
        current = current.next;
    }
    if(l1 ! =null) {
        while(l1 ! =null) {
            zhi = (l1.val + nextyu) % 10;
            current.next = new ListNode(zhi)
            nextyu = Math.floor((l1.val + nextyu) / 10);
            l1 = l1.next
            current = current.next
        }
    }
    if(l2 ! =null) {
        while(l2 ! =null) {
            zhi = (l2.val + nextyu) % 10;
            current.next = new ListNode(zhi)
            nextyu = Math.floor((l2.val + nextyu) / 10);
            l2 = l2.next
            current = current.next
        }
    }
    if(nextyu ! =0) {
        current.next = new ListNode(nextyu)
    }
    return newlist.next
};
Copy the code