reverse the position of integer digits?

后端 未结 13 2511
予麋鹿
予麋鹿 2021-02-09 15:00

i have to reverse the position of integer like this

input = 12345

output = 54321

i made this but it gives wrong output e.g 5432

#include         


        
相关标签:
13条回答
  • 2021-02-09 15:17

    Here is a solution

        int num = 12345;
        int new_num = 0;
        while(num > 0)
        {
                new_num = new_num*10 + (num % 10);
                num = num/10;
        }
        cout << new_num << endl;
    
    0 讨论(0)
  • 2021-02-09 15:17

    This is a coding assignment for my college course. This assignment comes just after a discussion on Operator Overloading in C++. Although it doesn't make it clear if Overloading should be used for the assignment or not.

    0 讨论(0)
  • 2021-02-09 15:20

    If you try it once as an example, you'll see your error.

    Input: 12

    first loop:

    out: 12%10 = 2 / 1 = 2
    i = 100
    test: 12/100 = 0 (as an integer)

    aborts one too early.

    One solution could be testing

    (num % i) != num

    Just as one of many solutions.

    0 讨论(0)
  • 2021-02-09 15:24
    int _tmain(int argc, _TCHAR* argv[])
    {
    int x = 1234;
    int out = 0;
    while (x != 0)
    {
        int Res = x % (10 );
        x /= 10;
        out *= 10;
        out +=  Res;
    }
    cout << out;
    
    
    } 
    
    0 讨论(0)
  • 2021-02-09 15:26

    Well, remember that integer division always rounds down (or is it toward zero?) in C. So what would num / i be if num < 10 and i = 10?

    0 讨论(0)
  • 2021-02-09 15:26

    I have done this simply but this is applicable upto 5 digit numbers but hope it helps

     #include<iostream>
        using namespace std;
    void main()
    { 
        int a,b,c,d,e,f,g,h,i,j;
        cin>>a;
        b=a%10;
        c=a/10;
        d=c%10;
        e=a/100;
        f=e%10;
        g=a/1000;
        h=g%10;
        i=a/10000;
        j=i%10;
        cout<<b<<d<<f<<h<<j;
    }`
    
    0 讨论(0)
提交回复
热议问题