noodleProblems/
Reverse Integer
#07

Reverse Integer

AlgorithmmediumMath

Given a signed 32-bit integer x, return x with its digits reversed. The sign is preserved, so reversing a negative number stays negative.

If reversing x produces a value that falls outside the signed 32-bit range [-2^31, 2^31 - 1], return 0 instead. Solve it without relying on 64-bit integer support.

Example cases

  • positive
    in x = 123
    out 321
    Reversing the digits of 123 gives 321.
  • negative
    in x = -123
    out -321
    The sign is kept, so -123 reverses to -321.
  • trailing zero
    in x = 120
    out 21
    Reversing 120 gives 021, and leading zeros are dropped to 21.
  • overflow
    in x = 1534236469
    out 0
    Reversed this is 9646324351, which exceeds 2^31 - 1, so the result is 0.

Constraints

  • -2^31 <= x <= 2^31 - 1
Saved
x =
123