Reverse Integer
MedPrompt
Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.
Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
Example 1:
Input: x = 123
Output: 321Example 2:
Input: x = -123
Output: -321Example 3:
Input: x = 120
Output: 21
Constraints:
-231 <= x <= 231 - 1
Approaches
2 approaches with complexity analysis and trade-offs.
This approach converts the integer to a string, reverses the string, and then converts it back to an integer. It handles the sign separately and uses a try-catch block to detect overflow during the final conversion, which respects the constraint of not using 64-bit integers.
Algorithm
- Determine the sign of the input integer
x. If it's negative, store the sign and proceed with the absolute value ofx. - Convert the absolute value of
xto its string representation. - Create a new
StringBuilderfrom the string and use itsreverse()method to reverse the digits. - Convert the reversed
StringBuilderback to a string. - Use a
try-catchblock to parse the reversed string back into an integer usingInteger.parseInt(). - Inside the
tryblock, if the parsing is successful, multiply the result by the original sign and return it. - If a
NumberFormatExceptionis caught, it means the reversed number is too large to fit in a 32-bit integer. In this case, return0.
Walkthrough
The core idea is to leverage built-in string manipulation functions. First, we handle the sign. If the number x is negative, we note this and proceed with its absolute value. Then, we convert this positive number into a string. The StringBuilder class provides a convenient reverse() method, which we use to reverse the string of digits. Finally, we attempt to parse this reversed string back into an integer. The Integer.parseInt() method will throw a NumberFormatException if the string represents a value outside the [-2^31, 2^31 - 1] range. By wrapping this parsing operation in a try-catch block, we can gracefully handle the overflow case by returning 0 from the catch block. If parsing succeeds, we re-apply the original sign to the result.
class Solution { public int reverse(int x) { String s = String.valueOf(x); String reversedS; int sign = 1; if (x < 0) { sign = -1; s = s.substring(1); // Remove the '-' sign } reversedS = new StringBuilder(s).reverse().toString(); try { int result = Integer.parseInt(reversedS); return result * sign; } catch (NumberFormatException e) { // This exception is thrown if the reversed string represents a number // larger than Integer.MAX_VALUE. return 0; } }}Complexity
Time
O(log10(x))
Space
O(log10(x))
Trade-offs
Pros
Conceptually simple and easy to implement.
Leverages built-in string manipulation and parsing functions, making the code concise.
Cons
Less efficient due to the overhead of type conversions between integer and string.
Requires extra space proportional to the number of digits to store the string representation.
Solutions
Solution
public class Solution { public int Reverse(int x) { int ans = 0; for (; x != 0; x /= 10) { if (ans < int.MinValue / 10 || ans > int.MaxValue / 10) { return 0; } ans = ans * 10 + x % 10; } return ans; }}Video walkthrough
Newsletter
One sharp idea, every week
System design and interview prep — short enough to finish.
No spam. Unsubscribe anytime.
Practice
Same difficulty — related problems to reinforce the pattern.