Do you mean, if you enter 123 it should output 321?
Try this algorithm:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
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:
1 2 3 4 5 6 7
int pow (int num, int exp)
{
int out = 1;
while (exp-- > 0)
out *= num;
return out;
}
Edit: I just tested it, it works.
1 2 3 4 5 6 7 8 9 10 11
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 . . .
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..
Here I started off by findign the number of digits. I did this with:
1 2 3
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:
1 2
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