7/670

7. Reverse Integer

Medium

You are given a signed 32-bit integer x. Return the value you get by reversing the order of its digits, keeping the sign in place.

The catch (this is what makes LeetCode #7 more than a string trick): the environment can only hold signed 32-bit integers, i.e. values in the range [-2^31, 2^31 - 1]. If reversing the digits produces a number that falls outside that range, return 0 instead. Assume you are not allowed to use any wider 64-bit type to store the final answer.

Reversing drops any leading zeros naturally: 120 becomes 21, not 021. A negative sign is preserved, so -123 reverses to -321.

Example 1:

Input: reverse_integer(123)

Output: 321

Explanation: The digits 1, 2, 3 reverse to 3, 2, 1, giving 321, which fits in 32 bits.

Example 2:

Input: reverse_integer(-123)

Output: -321

Explanation: The sign is preserved and the digits 1, 2, 3 reverse to 321, so the answer is -321.

Example 3:

Input: reverse_integer(120)

Output: 21

Explanation: Reversing 120 gives 021, the leading zero drops off, leaving 21.

Constraints:

  • -2³¹ ≤ x ≤ 2³¹ - 1
  • The environment stores only signed 32-bit integers, a reversed value outside [-2³¹, 2³¹ - 1] must yield 0.
  • You may not rely on a 64-bit type to hold the final answer (the pure approach shows how).

Hints:

Peel digits off the end with `% 10` and shrink the number with integer division by 10 until it reaches 0.

Handle the sign separately (or lean on the language's toward-zero division) so the reversal logic stays uniform.

To stay strictly 32-bit, check for overflow BEFORE you do `result = result * 10 + digit`: if `result` already exceeds `INT_MAX / 10`, the next push will overflow.

▶ Run checks these sample cases. Submit also runs hidden edge cases.

Input: x = 123

Expected output: 321