The two together
The subject setting
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.
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
Example 3:
Input: l1 =,9,9,9,9,9,9 [9], l2 =,9,9,9 [9] output:,9,9,9,0,0,0,1 [8]Copy the code
Algorithm analysis:
1. Initialize the current node as a dummy node for the return list
2. Initialize carry to 0
Sum = l1 + L2 + carry; sum = L1 + L2 + carry; sum = L1 + L2 + carry; sum = L1 + L2 + carry; sum = L1 + L2 + carry; Point L1 and L2 to the next node
4. Check whether carry>0 is valid. If yes, add a new node containing the number carry to the return list
5. Return the next node of the dummy node
JS solution code:
var addTwoNumbers = function(l1, l2) { let dummy = new ListNode(); let curr = dummy; let carry = 0; while(l1 ! == null || l2 ! == null){ let sum= 0; if(l1 ! == null){ sum += l1.val l1 = l1.next } if(l2 ! == null){ sum += l2.val l2 = l2.next } sum += carry; curr.next = new ListNode(sum % 10); carry = Math.floor(sum/10); curr = curr.next; } if(carry>0){ curr.next = new ListNode(carry); } return dummy.next; };Copy the code