reverse the position of integer digits?

后端 未结 13 2558
予麋鹿
予麋鹿 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:31

    If I were doing it, I'd (probably) start by creating the new value as an int, and then print out that value. I think this should simplify the code a bit. As pseudocode, it'd look something like:

    output = 0;
    
    while (input !=0)
        output *= 10
        output += input % 10
        input /= 10
    }
    print output
    

    The other obvious possibility would be to convert to a string first, then print the string out in reverse:

    std::stringstream buffer;
    
    buffer << input;
    
    cout << std::string(buffer.str().rbegin(), buffer.str().rend());
    

提交回复
热议问题