Reverse output

Title description
Use recursion to write a program that outputs a non-negative integer in reverse order. For example, input 1234 and output 4321 (without leading 0).
Input
Multiple groups of inputs, each group input a non-negative integer.
Output
Output the results in reverse order, each result occupies one line.
Sample input
12
1230
0
Sample output
21
321
0

Note:
The last 0 in 1.12030 is the leading after the reverse order and should not be output. But the previous 0 should be output as usual.
2. There is a bigger pit across this pit: the so-called leading does not necessarily refer to the last 0, for example, the 0 in 120000 should not be output.

Method one:
//Using the global variable array to store all values, and making a unified judgment in the main function, it may take a long time

#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
#define ll long long
#define N 150
using namespace std;
int num,s[N];
void Find(int n)
{
    
    
    if(n==0)return;
    else
    {
    
    
        s[num]=n%10;
        num++;
        Find(n/10);
    }
}
int main()
{
    
    
    int n;
    while(cin>>n)
    {
    
    
        num=0;
        if(n!=0)
        {
    
    Find(n);
        for(int i=0;i<num;i++)
            if(i==0&&s[i]==0)
            {
    
    
                while(!s[i]) i++;
                i--;
            }
            else
                cout<<s[i];
        }
        else cout<<n;
        cout<<endl;
    }
}

Method two:
//Use a variable flag to control whether the first bit of the output is 0, if it is not output, or if it is not, output the remainder when recursive.

#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
#define ll long long
#define N 150
using namespace std;
int solve(int n,int flag)
{
    
    
    if(n<10)
    {
    
    
        return n;
    }
    int a=n%10;//连续判断是否为前导0,是则不输出
    if(a!=0)
       flag=1;//发现不再出现0为前导时,将flag标记为1,往后正常输出
    if(flag)
        cout<<a;
    return solve(n/10,flag);
}


int main()
{
    
    
        int n;
        int flag=0;
        while(cin>>n)
           cout<<solve(n,flag)<<endl;//这里很明显的主函数进去的flag值在函数中做变化后不会影响主函数flag,因此无须在主函数每次循环中加个flag=0
        return 0;
}



Guess you like

Origin blog.csdn.net/m0_52380556/article/details/115264618