Thank you Arslan. This is really helpful. However I have a question, what does this line of code do : reversed = reversed*10 + x%10; |
The % operator (called modulo) returns remainder after division. Thus:
7 % 3 = 1 (3 goes into 7 twice, leaving a remainder of 1).
15 % 5 = 0 (5 goes into 15 thee times, leaving a remainder of 0).
This operator can come in really handy for manipulating integers. Anyway, you'll notice that modding any number by 10 will give you its last digit.
1 2 3 4 5 6
|
int reversed = 0;
while(x > 0)
{
reversed = reversed*10 + x%10; // take last digit of x, "appends" it to reversed
x /= 10; // remove last digit of x
}
|
Since
reversed starts off as 0, the result of the first iteration is that the last digit of x is simply added to 0. The last digit of x is then "removed" by dividing by 10.
After that, in the second iteration,
reversed is multiplied by 10 and the last digit of x is added to it. The last digit of x is then removed.
This is continued until x is 0.
The loop essentially takes advantage of how base 10 numbers work. To form any number, you can start at 0, and repeatedly by 10 and add each successive digit.
To get from 0 to 236 for example, you can do the following:
0*10 + 2 = 2;
2*10 +3 = 23;
23*10 + 6 = 236.
This is what the loop above is doing, except its always adding the last digit of x, thus resulting in the reverse of x.