150NeetCode 150

150.Reverse Integer

MediumBit Manipulation ยท 7/7
LeetCode #7Video

Problem

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 range [-2^31, 2^31 - 1], return 0.

Assume the environment does not allow you to store 64-bit integers (signed or unsigned) โ€” so you must detect overflow before it happens using only int arithmetic.

Examples

Input:  x = 123
Output: 321
Input:  x = -123
Output: -321
Explanation: The sign is kept; only the digits are reversed.
Input:  x = 120
Output: 21
Explanation: The reversed number 021 has its leading zero dropped.
Input:  x = 1534236469
Output: 0
Explanation: Reversed it would be 9646324351, which is larger than 2^31 - 1 = 2147483647.

Constraints

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

๐Ÿ’ก Key Insight

Reverse arithmetically: repeatedly pop the last digit with x % 10 (and x /= 10), and push it onto the result with res * 10 + digit. The only danger is the push step overflowing, so check before pushing: if res > MAX / 10 (or res == MAX / 10 and digit > 7), the next push would exceed 2147483647; symmetrically for the negative bound -2147483648. Java's % keeps the sign of x, so negatives work without special-casing.

Brute Force (String Reversal)

TimeO(d) where d โ‰ค 10 is the number of digitsSpaceO(d) for the strings; also relies on exceptions for control flow, which is slow and frowned upon.

Intuition

Turn the number into a string, reverse its digits, put the sign back, and let Integer.parseInt tell us whether it fits: it throws NumberFormatException on overflow, which we map to 0.

Algorithm

  1. s = Integer.toString(x); note whether it starts with '-'.
  2. Reverse the digit part.
  3. Prepend '-' if needed and parse with Integer.parseInt.
  4. If parsing throws, return 0.

Visualization

x = -123  โ†’ "-123" โ†’ digits "123" โ†’ reversed "321" โ†’ "-321" โ†’ -321
x = 1534236469 โ†’ "9646324351" โ†’ parseInt throws โ†’ 0

Code

java
class Solution {
    public int reverse(int x) {
        String s = Integer.toString(x);
        boolean negative = s.charAt(0) == '-';
        String digits = negative ? s.substring(1) : s;
        String reversed = new StringBuilder(digits).reverse().toString();
        try {
            // parseInt rejects anything outside the 32-bit range
            return Integer.parseInt(negative ? "-" + reversed : reversed);
        } catch (NumberFormatException e) {
            return 0;
        }
    }
}

Complexity

  • Time: O(d) where d โ‰ค 10 is the number of digits โ€” O(1) in practice.
  • Space: O(d) for the strings; also relies on exceptions for control flow, which is slow and frowned upon.

Complexity Comparison

Approach Time Space
String Reversal O(d) O(d)
64-bit Accumulator O(log10 |x|) O(1)
Pop and Push with Pre-Check O(log10 |x|) O(1)

Common Pitfalls

  • Checking for overflow after res * 10 + digit โ€” in Java the value has already wrapped around silently, so the check is meaningless.
  • Taking Math.abs(x) first โ€” Math.abs(Integer.MIN_VALUE) is still Integer.MIN_VALUE (it overflows), breaking the logic. Let % and / handle the sign.
  • Forgetting trailing zeros: 120 must become 21; the arithmetic approach handles this naturally because leading zeros contribute nothing.
  • Assuming x % 10 is always non-negative โ€” in Java it takes the sign of x, which is exactly why the negative guard compares against -8.