Reverse Integer

Updated on 01 July, 2025
Reverse Integer header image

Problem Statement

In this task, a signed 32-bit integer x is provided, and the objective is to return the number with its digits reversed. This task, however, comes with specific challenges that hinge upon data format and overflow issues. Reversing the digits of x may sometimes result in a number that exceeds the boundaries of a 32-bit signed integer range, which is [-2^31, 2^31 - 1]. If the reversed integer exceeds this range, the function should return 0 instead of the out-of-range integer. Moreover, this problem must be solved under the constraint that the environment only supports 32-bit integers, effectively prohibiting the use of 64-bit integers to easily tackle overflow scenarios.

Examples

Example 1

Input:

x = 123

Output:

321

Example 2

Input:

x = -123

Output:

-321

Example 3

Input:

x = 120

Output:

21

Constraints

  • -231 <= x <= 231 - 1

Approach and Intuition

Reversing the digits of a number seems straightforward but requires careful handling of the integer overflow and the presence of negative numbers. Here's a strategy to achieve the reversal without inadvertently causing overflow:

  1. Handle the input number as per its sign (positive or negative).
    • If the number is negative, process it as a positive number temporarily and reintroduce the sign at the end.
  2. Extract each digit from the number and construct the reversed number:
    • Initialize a result variable to 0.
    • Utilize a loop to pop the last digit of the current number and push it to the next position in result:
      • Multiply result by 10 (shifting digits left).
      • Add the extracted last digit of the number.
  3. Check for overflow during each iteration:
    • Before appending a digit, check if result is about to exceed or meet the overflow criterion. This can be done by comparing result against a pre-determined safe limit (2^31 / 10 for positive numbers and (-2^31 - digit) / 10 for negative numbers after adjusting for the current digit).
    • If an overflow is detected, return 0 immediately.
  4. Return the correctly signed reversed number:
    • If the original number was negative, multiply the result by -1.

By using the above method, we ensure that the solution adheres to the 32-bit environment constraints and correctly handles all the given examples and potential edge cases like overcoming the challenge posed when x is 0 or when reversing results in a number like 120 becoming 21, dismissing the insignificant zero.

Solutions

  • C++
  • Java
  • C
  • JavaScript
  • Python
cpp
class Solution {
public:
    int reverseInt(int x) {
        int reversedNumber = 0;
        while (x != 0) {
            int remainder = x % 10;
            x /= 10;
            if (reversedNumber > INT_MAX / 10 || (reversedNumber == INT_MAX / 10 && remainder > 7))
                return 0;
            if (reversedNumber < INT_MIN / 10 || (reversedNumber == INT_MIN / 10 && remainder < -8))
                return 0;
            reversedNumber = reversedNumber * 10 + remainder;
        }
        return reversedNumber;
    }
};

The provided C++ solution defines a function that reverses an integer and handles special cases such as overflow and underflow. The function works by extracting digits from the input integer, appending them to a new reversed integer, and ensuring the result stays within the valid integer range.

  • Extract the last digit of the input number using modulus operation.
  • Determine if adding another digit would cause overflow or underflow before actually adding the digit.
  • Append the digit by multiplying the reversed number by 10 and adding the digit.
  • Repeat the steps until all digits are processed or an overflow/underflow condition is detected.
  • If the reversed number is beyond the range of a 32-bit signed integer, the function returns 0.

The algorithm ensures that any reversal that causes the number to exceed the limits of a 32-bit signed integer results in an immediate return of 0, thus preventing potential overflow errors. This approach is efficient for handling the reversal of integers in compliance with constraints typically found in programming environments that use 32-bit integers.

java
class Solution {
    public int reverseInteger(int num) {
        int reversed = 0;
        while (num != 0) {
            int remainder = num % 10;
            num /= 10;
            if (
                reversed > Integer.MAX_VALUE / 10 ||
                (reversed == Integer.MAX_VALUE / 10 && remainder > 7)
            ) return 0;
            if (
                reversed < Integer.MIN_VALUE / 10 ||
                (reversed == Integer.MIN_VALUE / 10 && remainder < -8)
            ) return 0;
            reversed = reversed * 10 + remainder;
        }
        return reversed;
    }
}

This Java program implements a method to reverse a given integer. It handles the reversal by concatenating the digits of the input number in reverse order and manages potential overflow issues specific to signed integers in Java.

  • Initialize reversed as 0 to store the reversed number.
  • Use a while loop to iterate through the digits of the number using the modulus operator.
  • Extract the last digit of num using num % 10 and then shrink num by a factor of 10.
  • Check if appending another digit causes reversed to overflow or underflow, which is critical for maintaining integer integrity, especially given Java's fixed-size integer limits.
  • Multiply reversed by 10 and then add the extracted digit, effectively shifting the reversed number's digits to the left as new digits are added.
  • If a reversal causes an integer overflow or underflow, the function returns 0.
  • Finally, return the reversed integer once num is completely processed.
c
int reverse_number(int number) {
    int reversed = 0;
    while (number != 0) {
        int digit = number % 10;
        number /= 10;
        if (reversed > INT_MAX / 10 || (reversed == INT_MAX / 10 && digit > 7)) return 0;
        if (reversed < INT_MIN / 10 || (reversed == INT_MIN / 10 && digit < -8)) return 0;
        reversed = reversed * 10 + digit;
    }
    return reversed;
}

The solution provided describes a function to reverse an integer in the C programming language. The function reverse_number takes a single integer parameter and returns its reversed counterpart. The reversal process is executed using a while loop that continues until the original number is reduced to zero.

Here's how the function executes:

  1. Initialize a variable reversed to store the reversed number, starting with zero.
  2. Enter a while loop which runs as long as the input number is not zero.
  3. Extract the last digit of the number using modulo operation (number % 10) and then reduce the number by dividing it by 10.
  4. Before appending the digit to the reversed number, check for potential overflow or underflow. This step ensures that the function does not encounter an integer overflow or underflow, which is critical when dealing with the fixed size of integers in C:
    • Check if reversed exceeds INT_MAX / 10, or meets INT_MAX / 10 while the digit is greater than 7, indicating a possible overflow if another digit is added.
    • Similarly, check if reversed is less than INT_MIN / 10, or meets INT_MIN / 10 and the digit is less than -8, indicating a possible underflow.
    • If any of the above conditions are true, the function returns 0.
  5. If there are no overflow/underflow risks, multiply reversed by 10 and add the current digit to it.
  6. After the loop concludes, return the reversed integer.

This approach effectively handles edge cases and ensures that the function returns a valid reversed integer or zero if reversing would cause an integer overflow or underflow. The function is designed to be robust against the common pitfalls associated with manipulating integers, like exceeding the numeric bounds of the variable's type.

js
var reverseInteger = function (num) {
    let reversed = 0;
    while (num !== 0) {
        let digit = num % 10;
        num = (num - digit) / 10;
        if (
            reversed > 214748364 ||
            (reversed == 214748364 && digit > 7)
        )
            return 0;
        if (
            reversed < -214748364 ||
            (reversed == -214748364 && digit < -8)
        )
            return 0;
        reversed = reversed * 10 + digit;
    }
    return reversed;
};

The solution provided for the problem "Reverse Integer" is written in JavaScript. This function reverses a given integer by manipulating numerical operations.

Follow these steps to understand how the function operates to reverse an integer:

  1. Initialize reversed to zero. This variable will store the reverse of the original number.
  2. Use a while loop to iterate until the number, num, is reduced to zero.
  3. Inside the loop, extract the last digit of num using num % 10.
  4. Adjust num to remove the last digit ((num - digit) / 10).
  5. Check for overflow conditions before reversing a large integer. If the reverse value exceeds the bounds of a 32-bit signed integer, return 0 to indicate overflow.
  6. If no overflow conditions are met, update reversed by multiplying the current reversed value by 10 and adding the digit.
  7. After the loop completes, return the value stored in reversed.

This approach ensures that the integer is correctly reversed within the bounds of a 32-bit signed integer. It handles both positive and negative numbers by leveraging integer division and modulus operations effectively.

python
class Solution:
    def reverse_integer(self, number: int) -> int:
        polarity = [1, -1][number < 0]
        reversed_num, number = 0, abs(number)
        while number:
            number, remainder = divmod(number, 10)
            reversed_num = reversed_num * 10 + remainder
            if reversed_num > (2**31 - 1):
                return 0
        return polarity * reversed_num

The given Python code efficiently reverses an integer while handling specific constraints. It defines a method, reverse_integer, within a Solution class to process an integer number and return its reversed version.

  • The function begins by determining the polarity or sign of the number using a list indexing technique. It checks if the number is negative (number < 0), and sets polarity to -1 if true, and 1 otherwise.
  • It then strips the number of its sign for ease of manipulation by taking its absolute value.
  • Using a while loop, the function extracts each digit from the number by using divmod to divide the number by 10. The remainder from divmod gives the current digit, which is then used to construct the reversed number.
  • The reversed number is recalculated by shifting its digits to the left (multiplying by 10) and adding the new digit.
  • A critical check ensures that the reversed number does not exceed 32-bit signed integer range. If it does, the function immediately returns 0, adhering to overflow rules.
  • Finally, the function returns the reversed number adjusted for its original polarity.

This method efficiently reverses the integer within 32-bit constraints and smoothly handles numerical overflow by returning zero, ensuring robust performance across all inputs.

Comments

No comments yet.