~/problems / Math & matrices

Reverse Integer

medium ~20 min

Write reverse_digits(x) -> int that takes a 32-bit signed integer and returns the number whose decimal digits are those of x in reverse order, keeping the sign. Leading zeros that appear after reversing are dropped (120 becomes 21).

If the reversed value does not fit in a 32-bit signed integer, that is outside [-2^31, 2^31 - 1] = [-2147483648, 2147483647], return 0.

reverse_digits(1234)          # 4321
reverse_digits(-560)          # -65
reverse_digits(0)             # 0
reverse_digits(1463847412)    # 2147483641
reverse_digits(1534236469)    # 0   (9646324351 is too big)
  • -2^31 <= x <= 2^31 - 1.
  • Pretend your machine only has 32-bit signed integers: don't build the reversed number in a wider type or via a string and range-check it afterwards. Detect the overflow before it would happen.
  • Aim for O(number of digits) time and O(1) extra space.
Show hint

you build the answer as result * 10 + digit. Before doing that step, compare result with the largest (or smallest) value that can still be multiplied by ten safely.

Topic: Math and matrices. Digit-by-digit arithmetic, matrix rotation and in-place tricks.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc