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.
r = 0 r = r * 10 + 3 # 3 r = r * 10 + 8 # 38 r = r * 10 + 1 # 381
Take 1: r = 0 × 10 + 1 = 1.
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.
r = 0
while n > 0:
r = r * 10 + n % 10
n //= 10
return rr is 52 and the next digit is 7. What is r after r = r × 10 + 7?
- A527
- B59
- C752
Show the answer
527. 52 × 10 = 520 makes room, and adding 7 fills the new last place.
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.
n = 381 → 183
0 ≤ n ≤ 2,147,483,647