DSA Factory
Free lessonsMath and bits · Stage 0 · Digits and divisibility · Step 2

Build a number digit by digit

Reverse a number by pushing digits onto the end of a new one. About 7 minutes.

Make room, then add

Picture typing a number on a calculator: you press 3, then 8, then 1, and the screen shows 381. Each new digit pushes everything already there one place to the left.

That is multiplying by 10 to make room, then adding the new digit. Starting from 0 you get 3, then 38, then 381.

Multiply by 10, then add: to put a digit on the end.
In code
r = 0
r = r * 10 + 3   # 3
r = r * 10 + 8   # 38
r = r * 10 + 1   # 381
Reverse 381
3
0
8
1
1
2
digit

Take 1: r = 0 × 10 + 1 = 1.

Move 1 of 3

Last out, first in

Now read the digits of another number from its right end and type each one into the calculator. The last digit is typed first, so it ends up first in the result, and the whole thing comes out reversed.

Zeros at the end of the original become leading zeros in the result, and leading zeros simply vanish: 120 reverses to 21.

Watch the size: reversing 2,147,483,647 gives 7,463,847,412, too big for a 32-bit int.
In code
r = 0
while n > 0:
    r = r * 10 + n % 10
    n //= 10
return r
Quick check

r is 52 and the next digit is 7. What is r after r = r × 10 + 7?

  1. A527
  2. B59
  3. C752
Show the answer

527. 52 × 10 = 520 makes room, and adding 7 fills the new last place.

Your problem

Reverse the digits

Return the number you get by reading the digits of n backwards. Zeros that end up at the front vanish, so 1200 becomes 21. The result can be bigger than an int, so return a long.

Example
n = 381 → 183

0 ≤ n ≤ 2,147,483,647

Solve it in your browserPython, C++, Java or JavaScript. Hints if you get stuck. No sign-up needed.
Start coding