Article From:https://segmentfault.com/q/1010000012137806

There is a programming question, which outputs all the symmetry numbers within 1993, and uses pointer and function to implement. There is no train of thought. Is there any good plan?

Answer 0:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

//** Declarations structure/ / * * * @result returns an array of symmetric numbersThe length of the / * * * @length arrayStruct Symmetrical {Int *result;Int length;};Typedef struct Symmetrical Symmetrical;Symmetrical *findSymmetrical () {/ / allocate memory for results. The maximum probability is for all numbers.It is a symmetric number, that is, sizeof (int) *1993Int *result = (int *) malloc (sizeof (int) *1993);Int length = 0;/An array that is stored after a number is converted to a stringChar *numStr = (char *) malloc (sizeof (char) *4);For (int i = 1; I < =1993; i++) {/ / if less than 10, it must be a symmetric numberIf (I < 10) result[length++] = I;Else {Int is_symmetrical = 1;/ / convert numbers to strings. Itoa is a non-standard function. Sprintf can be used instead.Sprintf(numStr, "%d", I);/ / Itoa (I, numStr, 10);Int num_length = strlen (numStr);/ / / for each oneFor (int j = 0; J < num_length / 2; j++) {/ / asThe difference between the J and the J of the positive number is not symmetric.If (numStr[j]! = numStr[num_length - J - 1]) {Is_symmetrical = 0;Break;}}/ / if it's a symmetric number, save it in the result arrayIf (is_symmetrical) result[length++] = I;}}Free (numStr);/ / create symmetric number structure for simultaneous transfer of array and array lengthSymmetrical *symmetrical = (Symmetrical *) MAlloc (sizeof (Symmetrical));Symmetrical-> result = result;Symmetrical-> length = length;Return symmetrical;}Int main () {Symmetrical *result = findSymmetrical ();/ / printFor (int i = 0; I < result-> length; i++) {Printf ("%d", result-> result[i]);}Free (result-> result);Free (result);}

The answer is not optimal, but the idea is.

Link of this Article: C language programming problem

Leave a Reply

Your email address will not be published. Required fields are marked *