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

Hope is a good thing, maybe the best of things. And no good thing ever dies.

The sum of two Numbers

The title

Given an integer array nums and an integer target value target, find the two integers in the array and the target value target and return their array subscripts.

Example 1:

Nums = [2,7,11,15], target = 9 output: [0,1]Copy the code

Example 2:

Input: nums = [3,2,4], target = 6Copy the code

Example 3:

Input: nums = [3,3], target = 6Copy the code

The problem solving

Double for loop plus judgment

Loop through the number group, through two layers of traversal, recycle in the inner layer to judge whether two values meet the requirements of the result.

var twoSum = function (nums, target) { let x; let y; let arr = [x, y]; for (x = 0; x < nums.length; X ++) {// For (y = x+ 1; y < nums.length ; y++) { if (nums[x] + nums[y] == target) { arr[0] = x; arr[1] = y; } } } return arr; };Copy the code

The two together

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.

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

The problem solving

Since both input lists store digits in reverse order, numbers in the same position in the two lists can be added directly.

We iterate over both lists at the same time, calculating their sum bit by bit and adding it to the carry value of the current position.

var addTwoNumbers = function (l1, l2) { let d = new ListNode(-1); // let p = d; // Move p, why not move d? Let flag = 0; / / carry while (l1 | | l2) {/ / loop jump out of the condition that both list is empty, not empty or have a another corresponding node value is 0 let a = l1 && l1. Val, b = l2 && l2. Val;; l1 = l1 ? l1.next : null,l2 = l2 ? l2.next : null; Let sum = (a + b + flag) % 10; // let sum = (a + b + flag) % 10; Math.floor((a + b + flag) / 10); P.ext = new ListNode(sum); // Create a new node p = p.ext; } if (flag! == 0) p.next = new ListNode(flag); Return d.next; };Copy the code

conclusion

The attached:

  • The sum of two Numbers
  • The two together

If this article helped you, please like 👍 and follow ⭐️.

If there are any errors in this article, please correct them in the comments section 🙏🙏

Welcome to pay attention to my wechat public number, exchange technology together, wechat search 🔍 : “fifty years later”