# Integers reversed.....

• 02-04-2006
darren200184
Integers reversed.....
How do I reverse numbers or words to be backwords after I input those numbers or words.

Like say I input 5789, how do I make it come back out as 9875?

Any help would be much appreciated, thanks.
• 02-04-2006
Daved
If it is stored as a string, you can use the reverse algorithm. If it is a number, you have to do some math to get each digit and then create a new number with the digits reversed, or you can convert it to a string, reverse it, and convert it back.
• 02-04-2006
Richie T
there's a simple way if you are strictly dealing with ints. i know
that the methods described already are more robust, but just to
point out that things can be done a little differently, try a loop like
this:

Code:

```while (num/10 != 0 || num%10 != 0) {          printf ("%d", num%10);         num = num/10; }```
this reverses the order of the number, but any leading 0's are
ignored. the looping condition allows the handling of 0's within
the number and prevents a loop that either finishes too early or
runs infinitely. limited functionality, but conveniently simple.
• 02-04-2006
darren200184
I got it now, thanks guys.
• 02-04-2006
w00tw00tkab00t
i wrote a function to reverse a string, i used it in my base conversion algorithm, use this if you want:

Code:

```std::string revstr(std::string str) {   char tmp;   int l = str.length(), l2 = l - 1, ong;   for (ong = 0; ong < (l / 2); ong ++) {     tmp = str[ong];     str[ong] = str[l2 - ong];     str[l2 - ong] = tmp;   }   return str; }```
it's not too efficient but it's good enough for me.
• 02-04-2006
Daved
Why would you use that to reverse a string when you can use reverse?
Code:

`std::reverse(str.begin(), str.end());`
• 02-04-2006
iMalc
No need to convert to a string first...
Code:

```unsigned int reverseDecimalInteger(unsigned int x) {     unsigned int result = 0;     do {         result = result * 10 + x % 10;         x /= 10;     } while (x > 0);     return result; }```
• 02-05-2006
w00tw00tkab00t
well mine was originally from C, and i didn't know that C++ had a reverse funtion...... i just used it when i ported one of my programs from C -> C++.