Sorry I didn't get back to you sooner, I was out of town. Anyhow, I'm assuming you mean to do this in more than one line of code.
So, on with how to tackle this. kanarde explained how the division (/) and modulus (%) operators work on integers--so, I'll just skip over that much. First the number you proposed, 12345, is an integer base ten. Therefore, dividing the integer 12345 by 10 results in 1234 and taking the modulus of 12345 and 10 yields 5. Following this, we can take the modulus of 1234 and 10 (which is 4) and add it to the previous result (5) times 10, yielding 54. We can continue this until the whole number reverses. Here is a code example:
Code:
#include <iostream>
int reverse_int(int);
int reverse_int(int input){
int output = 0; // Workspace for the
// reversed int to be built
// While there are more
// digits to deal with, loop...
while(input != 0){
// First, use modulus (%) and
// add the remainder to the output times ten...
output = (output * 10) + (input % 10);
// Next, divide input by ten to get rid of the
// digit we just "appended" to the output...
input /= 10;
} // End while
return output;
} // End reverse_int()
int main(int argc, char *argv[]){
int i = 12345;
cout << i
<< " reversed is "
<< reverse_int(i)
<< '\n'
<< ends;
i = 123456789;
cout << i
<< " reversed is "
<< reverse_int(i)
<< '\n'
<< ends;
} // End main()
Keep in mind, however, this does not deal with the case of a number that--in its original form--is a multiple of ten. For instance, 1230 will reverse to 321, because base ten numbers--in C/C++--have no leading zeroes. Only base eight (octal) numbers have leading zeroes (and base sixteen (hexadecimal) numbers are represented with a leading 0x).
The easiest way around this is to prepend a zero when the modulus of original integer and ten equals zero. Here is a modified version of the main() from above that does just that.
Code:
// Includes and reverse_int() here...
int main(int argc, char *argv[]){
int i = 123450;
cout << i
<< " reversed is ";
// Deal with the the case
// where i is a multiple of 10...
if((i % 10) == 0)
cout << 0;
cout << reverse_int(i)
<< '\n'
<< ends;
i = 123456789;
cout << i
<< " reversed is ";
// Deal with the the case
// where i is a multiple of 10...
if((i % 10) == 0)
cout << 0;
cout << reverse_int(i)
<< '\n'
<< ends;
} // End main()
There are other ways to do this, probably much nicer than above, but this is probably the least complex--and it gets the job done.
Bookmarks