C language: Educoder-recursive method to convert an integer n into a string

Recursion method converts an integer n into a string

mission details

Use recursion to convert an integer n into a string, and then output it. When outputting, each character is required to be separated by a space. For example, if you enter 483, the string "4 8 3" should be output. The number of digits of n is uncertain and can be an integer of any number of digits.

Problem solving tips

1) If it is a negative number, convert it to a positive number, and artificially output a "-" sign.
2) You can use putchar(n%10+'0') or putchar(n%10+48) to output a character.
3) You can use putchar(32) to output a space.

AC code

#include<stdio.h>
void figureTrasform(int n){
    
    
    //在此写入函数体
    /*****************Begin******************/
	if(n < 0){
    
    
		n = -n;
		putchar('-');
		putchar(32);
	}
	if(n / 10) figureTrasform(n / 10);
	
	putchar(n % 10 + 48);
	putchar(32);
    /***************** End ******************/ 
}

//注意主函数以在题目中给出 
int main(){
    
    
    long n;
    scanf("%d", &n);
    if(n==0){
    
          //如果输入的n是0,则输出‘0’,结束。 
        putchar('0'); 
        return 0;
    }    
    figureTrasform(n);   //调用数字转换函数 
    return 0;
}

Note: Recursive functions are easier to understand backwards

Guess you like

Origin blog.csdn.net/m0_51354361/article/details/113780763