๐ŸŒ€ Reverse Integer โ€“ LeetCode Problem #7 (Explained Simply)

NatureNature
4 min read

One of the classic coding interview questions is the Reverse Integer problem. It's a great problem to practice integer manipulation and boundary checking.


๐Ÿงฉ Problem Statement

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], return 0.

โœ… Examples

  • Input: 123 โ†’ Output: 321

  • Input: -123 โ†’ Output: -321

  • Input: 120 โ†’ Output: 21


โš ๏ธ Constraints

A signed 32-bit integer means the number must lie within:

-2,147,483,648 to 2,147,483,647

If the reversed number exceeds this range, we return 0.


๐Ÿ‘ฃ Step-by-Step Approach

  1. Check if the number is negative.

  2. Take the absolute value of the number and reverse the digits.

  3. Convert the reversed string back to an integer.

  4. If the reversed number exceeds the 32-bit signed range, return 0.

  5. Otherwise, return the reversed number, keeping the sign correct.


๐Ÿงช Test Cases

InputOutput
123321
-123-321
12021
15342364690

๐Ÿ’ก PHP Solution

class Solution {
    function reverse($x) {
        // Check if the number is negative
        $isNegative = $x < 0;

        // Convert the number to positive and then to a string, reverse it
        $reverseNum = strrev(strval(abs($x)));

        // Convert the reversed string back to an integer
        $rev = (int)$reverseNum;

        // If the reversed number is more than 32-bit limit, return 0
        if ($rev > 2147483647) {
            return 0;
        }

        // If original number was negative, return negative reversed number
        return $isNegative ? -$rev : $rev;
    }
}

โœ… Explanation

  • abs($x) removes the negative sign.

  • strrev(strval(...)) reverses the number.

  • Type cast back to integer using (int).

  • Check overflow before returning.


๐Ÿ Python Solution

def reverse(x):
    # Check if number is negative (less than 0)
    negative = x < 0

    # Get the absolute value (e.g., -123 becomes 123)
    x = abs(x)

    # Convert number to string, reverse it, then turn it back into integer
    reversed_x = int(str(x)[::-1])

    # If reversed number is more than allowed 32-bit max value, return 0
    if reversed_x > 2**31 - 1:
        return 0

    # Add the negative sign back if original number was negative
    return -reversed_x if negative else reversed_x

โœ… Explanation

  • We reverse the number using Python slicing [::-1].

  • Overflow is handled by comparing with 2**31 - 1.


โ˜• Java Solution

public class Solution {
    public int reverse(int x) {
        // We'll use a long to safely store the reversed number
        long rev = 0;

        // Loop until x becomes 0
        while (x != 0) {
            // Get the last digit of x (e.g., 123 -> 3)
            rev = rev * 10 + x % 10;

            // Remove the last digit from x (e.g., 123 -> 12)
            x = x / 10;
        }

        // Check if reversed number is within 32-bit integer limits
        if (rev > Integer.MAX_VALUE || rev < Integer.MIN_VALUE) {
            return 0;
        }

        // Convert the long result back to int and return
        return (int) rev;
    }
}

โœ… Explanation

  • Use modulo % 10 to get last digit.

  • Use division / 10 to remove last digit.

  • Use a long for overflow check during the loop.


๐ŸŒ JavaScript Solution

var reverse = function(x) {
    // Check if number is negative
    let isNegative = x < 0;

    // Convert to positive, then to string, reverse it, and convert back to number
    let reversed = parseInt(Math.abs(x).toString().split('').reverse().join(''));

    // If reversed number exceeds the 32-bit max value, return 0
    if (reversed > 0x7FFFFFFF) return 0;

    // Return negative reversed number if input was negative
    return isNegative ? -reversed : reversed;
};

โœ… Explanation

  • Convert to string, reverse with split().reverse().join().

  • Use parseInt to convert back.

  • Check against max 32-bit integer (0x7FFFFFFF).


๐Ÿง  Key Learnings

  • Understand 32-bit integer overflow boundaries.

  • Always check for overflow after operations.

  • Use built-in methods (like strrev, slicing, or string reversal) smartly.

  • Optimize for time (O(log N)) and space (O(1) if done numerically).


๐Ÿ Final Thoughts

The Reverse Integer problem may seem simple at first, but it teaches you defensive programming, bit manipulation awareness, and working with edge cases.

This question is a great warm-up for more advanced number manipulation problems like Palindrome Numbers, Integer to Roman, or String to Integer.


0
Subscribe to my newsletter

Read articles from Nature directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Nature
Nature