“This is the 15th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”

[B] [C] [D]

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,4,3], l2 = [5,6,4] output: [7,0,8] explanation: 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

Tip:

  • The number of nodes in each linked list is in the range[1, 100] 内
  • 0 <= Node.val <= 9
  • The question data ensures that the numbers represented in the list do not contain leading zeros

The solution is as follows:

  1. Create a virtual head node to return a linked list of results
  2. createnumThe variable records the carry value of the sum of the previous node
  3. When at least one of the passed lists is not empty, the list is iterated to get the sum of the current loopsum = (l1? li.val:0) + (l2? l2.val:0) + num
  4. According to thesumCreate the next node ‘new ListNode(sum%10)
  5. Record carry valuesnum = Math.floor(sum/10)
  6. List the results,l1l2Go back one bit (if a list is empty, point tonull)
  7. When both lists are empty, judge whether the carry value is not zero at this time. If not, the carry value node is connected to the end of the result list according to the carry value node
  8. Returns the head node of the result list

A. sum B. sum C. sum D. sum

The code is as follows:

var addTwoNumbers = function(l1, l2) { const vhead = new ListNode(0); let num = 0, cur = vhead; while(l1||l2){ const sum = (l1? l1.val:0)+(l2? l2.val:0)+num; cur.next = new ListNode(sum%10) num = Math.floor(sum/10); cur = cur.next; l1 = l1? l1.next:null; l2 = l2? l2.next:null; } if(num) cur.next = new ListNode(num); return vhead.next; };Copy the code

At this point we are done with Leetcode -2- adding two numbers

If you have any questions or suggestions, please leave a comment!