Hey Pryious, glad you've gotten good help from us.
And I also really appreciate your method of asking questions. Only once every few months does a new member come by and ask a homework question in such a reasonable manner. I've grown so accustomed to seeing only a homework prompt being posted and nothing else (not even a statement asking us to do their homework, merely throwing out a question and expecting someone to answer.)
So to answer your question, you most certainly can reverse an int without using std::string.
The trick is in the modulus, or remainder, operator (%). The remainder of a number divided by 10 is the most significant digit of the number (farthest to the right). The remainder of 1234/10 = 4. The remainder of 123/10 = 3, etc, etc. Here's an example of how this is useful.
1 2 3 4 5 6 7 8 9 10 11
|
int number = 1234;
while(number != 0)
{
int mostSignificantDigit = number % 10; //is equal to the rightmost digit of number
cout << mostSignificantDigit << endl;
number /= 10; //(decrease the number by a factor of ten).
//number will equal zero when it divides a single digit number by 10
//because of how integer math is done.
}
|
So you could use this bit to create a vector or array of digits, then create a reversed int out of them by multiplying and adding proper digit place. (4 would turn into the thousands place, so newNumber += 4*1000, and 3 is the hundreds place, so newNumber += 3*100, etc).
EDIT:
Or use the recursive method below me.
Man recursion is cool. I can never wrap my brain around it, though.