Reverse Integer
Medium · Bit Manipulation · Math
Problem
Given a signed 32-bit integer x, return x with its digits reversed, keeping its sign: 123 becomes 321, -123 becomes -321, and 120 becomes 21. If the reversed value falls outside the signed 32-bit range — from -2147483648 (−2^31) to 2147483647 (2^31 − 1) — return 0.
The real rule is the one behind the problem: assume the machine cannot hold any integer outside that range, not even for a moment. Python’s integers never overflow, so reversing the digit string and checking the range at the end does give the right answer — but only by holding a number such as 9646324351 that a 32-bit machine could not store. The version an interviewer wants builds the result one digit at a time and checks, before each rev * 10 + digit, that the step stays in range.
Examples
Input: x = -123 Output: -321
The digits turn around and the minus sign stays in front.
Input: x = 1534236469 Output: 0
Reversed it would be 9646324351, far above 2147483647, so the answer is 0.
Constraints
- -2^31 <= x <= 2^31 - 1
- Only integers in that range may be stored, including along the way
Approaches
- Reverse the digit string, check at the end — time O(log |x|), space O(log |x|)
Related problems
Start free on Cariara · Coding problems · System design studio