This is the second day of my participation in Gwen Challenge

Today, I will spare some time to continue to work on leetcode. The difficulty of adding two numbers in the second question is medium, which is higher than the sum of the two numbers yesterday, but in fact, it is completely water, without turning at all from beginning to end.

The title

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.

Example 2: Input: L1 = [0], L2 = [0] Output: [0]

Train of thought

Essentially, it’s the sum of two numbers stored in an array. This problem is simpler than the general array number summation, because are stored in reverse, so, direct ones, tens, hundreds of continuous upward push are aligned, even find the decimal point to align the number of operations are not needed, directly from the first (lowest), add by bit, as shown in the figure

Pay attention to the point

There are two points to note:

  1. Two digits may have different lengths. If the two digits cannot be retrieved, the default value is 0
  2. And if you add the digits, especially if you add the largest digits, you might have two empty digits here, but because you added the last digits, you might have one more digit

Java version code

Class Solution {public ListNode addTwoNumbers(ListNode L1, ListNode l2) {// Result = null; ListNode current = null; ListNode current = null; // carry = 0; while (l1 ! = null || l2 ! = null) {// Default is 0 int val1 = 0; // if l1 is not empty, val if (l1! = null) { val1 = l1.val; } // int val2 = 0; if (l2 ! = null) { val2 = l2.val; } int sum = val1 + val2 + carry; carry = sum / 10; sum %= 10; if (result == null) { result = new ListNode(sum); current = result; } else { ListNode next = new ListNode(sum); current.next = next; current = next; } // l1 and l2 both point to the next node. = null) { l1 = l1.next; } if (l2 ! = null) { l2 = l2.next; } } if (carry > 0) { ListNode next = new ListNode(carry); current.next = next; } return result; }}Copy the code