Reverse Integer

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 [-2³¹, 2³¹ - 1], then return 0.

Example 1
Input: x = 123
Output: 321
Example 2
Input: x = -123
Output: -321
Explanation: Reversed digits of -123 is -321, which fits in 32-bit range.
Example 3
Input: x = 120
Output: 21
Explanation: Trailing zero is dropped after reversal.

Solution Approach

We extract digits one by one from the end of x and build the reversed number. Before each multiplication, we check whether the result would overflow the 32-bit signed integer bounds.

  • Pop digit: digit = x % 10, then x /= 10.
  • Before pushing: check if rev > Integer.MAX_VALUE / 10 or rev < Integer.MIN_VALUE / 10.
  • Push digit: rev = rev * 10 + digit.
  • Return (int) rev at the end.
Java
class Solution {
    public int reverse(int x) {
        long rev = 0;
        while (x != 0) {
            int digit = x % 10;
            x /= 10;
            rev = rev * 10 + digit;
            if (rev > Integer.MAX_VALUE || rev < Integer.MIN_VALUE) {
                return 0;
            }
        }
        return (int) rev;
    }
}
Complexity Analysis:

Time complexity: O(log x). Number of digits in x.
Space complexity: O(1). Only a few variables used.