Current location - Plastic Surgery and Aesthetics Network - Plastic surgery and beauty - //Convert an integer n into a string using recursion. For example, if you enter 483, the string "483" should be output. The number of digits in n is uncertain
//Convert an integer n into a string using recursion. For example, if you enter 483, the string "483" should be output. The number of digits in n is uncertain

char* function(int a); is a conversion function. When the integer parameter a is obtained, it will return a char pointer pointing to the target string,

The principle of this recursive function is:< /p>

1) Recursive intermediate step: If the current integer parameter a is not the ones digit. . Then substitute a/10 into char* function(int a); and wait for the called function to be jumped out, then store the lowest bit of the current integer parameter a into a string.

2) The lowest level of recursion: if the integer is a single digit, it is directly converted into ascii code; and stored in the character string. .

End of recursion

#include

char mychar[100];//Define an infinite character array to store the generated characters

int i=0 ; //Counter initialization

char* function(int a)//Define recursive function

{

if (a<10) // base case, The lowest case

{

mychar[i++]=char(48+a); //Convert to string using ASCⅡ code

return mychar ; //The function returns and the program runs to the next sentence of the statement that called it

}

function(a/10); //Recursively, change the last digit of the integer After elimination, enter the recursive function

mychar[i++]=char(48+a%10); //convert to string using ASCⅡ code

return mychar; //function Return, the program runs to the next sentence of the statement that called it

}

void main()

{

char*a ;

int num=0;

scanf("%d",&num);

a=function(num);

printf("After converting to string: %s",a);

}