### How to reverse a number?

I want to know how to reverse a number in a column, here is my code:
 ``12345678910111213`` ``````#include using namespace std; int main() { int n; do { cin>>n; n/10; cout<0); return 0; }``````
Bump.
 ``12`` ``````n/10; // This line doesn't do anything. cout << n % 10; // All this does is print out the remainder of n/10. ``````
Do you mean, if you enter 123 it should output 321?

Try this algorithm:
 ``12345678910111213141516`` ``````int Reverse(int num) { //get num digits int nb_digits = 0; while (num / pow(10,nb_digits) > 0) ++nb_digits; //add the digits, one at a time: int out = 0, iterator = nb_digits; while (iterator > 0) { out += num / pow(10,iterator-1) * pow(10,nb_digits-iterator); num %= pow(10,--iterator); } return out; }``````

make sure you have `int pow (int, int)` available. If it's not in <cmath>, make it:
 ``1234567`` ``````int pow (int num, int exp) { int out = 1; while (exp-- > 0) out *= num; return out; }``````

Edit: I just tested it, it works.
 ``1234567891011`` ``````int main() { while (true) { int in; cout << "Number: "; cin >> in; cout << "Reverse: " << Reverse(in) << endl; } return 0; }`````` ```Number : 1 Reverse: 1 Number : 123 Reverse: 321 Number : 164353 Reverse: 353461 Number : ^CPress any key to continue . . .```
Last edited on
#include<conio.h>
#include<iostream.h>
void main(void)
{
clrscr();
long i,num,rem;
cout<<"Enter a number";
cin>>num;
for(i=num;i>0;i=i/10)
{
rem=num%10;
num=num/10;
cout<<rem;
}
getch();
}
Can you guys explain how it works?
If you want to turn a number negative very simply, try this..

 ``1234`` ``````int number = 123; // Negate the number number -= number * 2;``````
yeah, it divides by 10 to the power of some number until it reaches its max size (so it knows how large the number is) then it does a similar feet, by finding the remainder of each division to produce its inverse..
Another way would be to convert it to a string and then go from there.. although the numeric way is probably much better
Here I started off by findign the number of digits. I did this with:
 ``123`` ``````int nb_digits = 0; while (num / pow(10,nb_digits) > 0) // number / 10^i > 0 ++nb_digits; // increase i ``````

Now that I know the number of digits, we can deal with each decimal place separately. If you want to know the 3rd digit you can do:
 ``12`` ``````num %= pow(10,3+1); // Get rid of large digits num /= pow(10,3); // Get rid of small digits ``````

We can use a for loop to go through all digits instead of just hard-coding the third digit.

Then we just put this digit in the spot we want it. If we have a 3-digit number and this represents the third digit, then we want to put it in the 1st digit place.
`output = num * pow(10,0); //Where 0 is the decimal place we want this to go to `
Topic archived. No new replies allowed.