Turn the digits around
EasyStuck?
Show a hintHide the hint
Take digits off the right of the input with %10 and /10, and add them to the right of the answer with answer * 10 + digit.
The ideas behind this problem
Last problem in this lesson
Go to the next lessonReverse the digits of a whole number. Reversing 4071 gives 1704.
Worked example#
Take digits off the right of the original and put them on the right of the answer.
| digit taken | what is left | answer before | answer after |
|---|---|---|---|
| 1 | 407 | 0 | 1 |
| 7 | 40 | 1 | 17 |
| 0 | 4 | 17 | 170 |
| 4 | 0 | 170 | 1704 |
The one line that matters#
answer = answer * 10 + digit
Multiplying by ten shifts everything already there one place left and leaves a space at the right. Adding the digit fills it. That is the opposite of / 10, which is what removes a digit.
The whole loop:
answer = 0
while n > 0:
answer = answer * 10 + (n % 10)
n = n / 10
Trailing zeros disappear, and that is correct#
Reversing 1200 gives 21, not 0021. A number has no leading zeros, so they are simply gone. Do not try to keep them.
Watch the size#
Reversing a number can make it larger than the one you started with. 1999999999 reversed is 9999999991, which does not fit in a 32 bit integer. The constraints below keep the answer inside 64 bits, so return a 64 bit type and the problem disappears.
Quietly overflowing is worse than failing, because the result looks like an answer.
Constraints#
0 <= n <= 2000000000- The answer fits in a signed 64 bit integer
Input
n is one whole number.
Output
The number with its digits reversed.
Examples
Input
4071
Output
1704
Digits come off the right and go on the right of the answer.
Input
1200
Output
21
The trailing zeros become leading zeros, which a number does not keep.
Input
0
Output
0
Nothing to reverse.
Something wrong with this problem? Report an issue
Ready to try it
Write your solution in C, C++, Java or Python and see every test case come back with the time and memory it took.
Free, and it stays free. No card.