Get the App
SLTechnology News&Howtos  ›  Development  › 

How to write code to realize the sum of two numbers

Shulou Source: shulou.com Published: 2022-06-03 07:02:41 10月19日 Update

This article focuses on "how to write code to achieve the sum of two numbers", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to write code to achieve the sum of two numbers.

I. explanation

Given an array of integers and a target value, find out the two numbers in the array that sum to the target value.

You can assume that each input corresponds to only one answer, and that the same element cannot be reused.

Example:

Given nums = [2,7,11,15], target = 9.

Because nums [0] + nums [1] = 2 + 7 = 9

So return [0,1]

II. Solution reference

1. Swift language

2. JavaScript language

3. Python language

4. Java language

5. C++ language

6. C language

# include # include struct object {int val; int index;}; static int compare (const void * a, const void * b) {return ((struct object *) a)-> val-((struct object *) b)-> val;} static int * twosum (int * nums, int numsSize, int target) {int I, j; struct object * objs = malloc (numsSize * sizeof (* objs)); for (I = 0; I

< numsSize; i++) { objs[i].val = nums[i]; objs[i].index = i; } qsort(objs, numsSize, sizeof(*objs), compare); int count = 0; int *results = malloc(2 * sizeof(int)); i = 0; j = numsSize - 1; while (i < j) { int diff = target - objs[i].val; if (diff >

OBJS [j] .val) {while (+ + I)

< j && objs[i].val == objs[i - 1].val) {} } else if (diff < objs[j].val) { while (--j >

I & & objs [j] .val = = objs [j + 1] .val) {}} else {results [0] = objs.index; results [1] = objs [j] .index; return results;}} return NULL;} int main (void) {/ / int nums [] = {- 1,-2,-3,-4,-5} / / int target =-8; / / int nums [] = {0rec 4je 3je 0}; / / int target = 0; int nums [] = {3,2,3}; int count = sizeof (nums) / sizeof (* nums); int target = 6; int * indexes = twosum (nums, count, target); if (indexes! = NULL) {printf ("% d% d", indexes [0], indexes [1]) } else {printf ("Not found");} return 0;} at this point, I believe you have a better understanding of "how to write code to achieve the sum of two numbers". You might as well do it in practice! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Tags: Language sum code content array goal target value learning practical deeper two elements interest practicality practical simple operation integers schemes methods more Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Technology Shulou Information Huawei macOS NVidia