Taro Logo

Reverse Integer

#1 Most AskedMedium
1 view
Topics:
Bit Manipulation

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: 321

Example 2:

Input: x = -123
Output: -321

Example 3:

Input: x = 120
Output: 21

Constraints:

  • -231 <= x <= 231 - 1

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. Are we guaranteed that the input $x$ is always a valid signed 32-bit integer?
  2. How should the reversal handle trailing zeros, such as reversing 120 to 021? Should the output be 21?
  3. When an overflow occurs and the reversed integer falls outside the signed 32-bit integer range $[-2^{31}, 2^{31}-1]$, should we return strictly 0?
  4. How should negative numbers be handled during reversal? For example, does $-123$ become $-321$?
  5. Are we allowed to use 64-bit integers internally to safely check for overflow before casting back, or are we restricted strictly to 32-bit operations?

Brute Force Solution

Approach

Imagine you have a number written down on a slip of paper and you want to read it backwards from right to left. The most straightforward approach is to pull off the last digit, write it down first, and repeat this process until you have moved every single digit to the new backward position.

Here's how the algorithm would work step-by-step:

  1. Take your starting number and isolate the very last digit on the far right.
  2. Write that isolated digit down as the beginning of your new reversed answer.
  3. Remove that digit from your original number so it is no longer part of the remaining pool.
  4. Look at the remaining number and repeat the process by grabbing its new last digit.
  5. Attach this new digit to the end of your growing reversed answer.
  6. Continue this exact process of grabbing the last digit and adding it to your reversed answer until no digits are left in the original number.
  7. Finally, check if the original number started out negative, and if so, make sure your newly built backward number is also negative.

Code Implementation

def reverse_integer(original_number):
    # We preserve the sign beforehand because modulo and division behave differently on negative integers
    is_negative = original_number < 0
    remaining_digits = abs(original_number)
    reversed_result = 0
    
    while remaining_digits > 0:
        last_digit = remaining_digits % 10
        reversed_result = (reversed_result * 10) + last_digit
        remaining_digits = remaining_digits // 10
        
    # We apply the 32-bit signed integer boundaries to comply with standard platform constraints
    if reversed_result > 2147483647:
        return 0
        
    # We restore the original sign back to the reversed digits to match the input polarity
    if is_negative:
        return -reversed_result
    
    return reversed_result

Big(O) Analysis

Time Complexity
O(log n) – The cost of the operation is driven by the number of digits in the input integer n, because we peel off one digit at a time using modulo and division by 10. For a number with n digits, the algorithm executes the digit-extraction loop exactly once for each digit. Since the number of digits in an integer is proportional to the base-10 logarithm of its value, the total operations scale logarithmically with the magnitude of the input. Thus, the work approximates log10(n) steps, which simplifies in Big O notation to O(log n).
Space Complexity
O(1) – The algorithm only utilizes a few primitive scalar variables, such as a running reversed number accumulator and a temporary digit holder, to extract and rebuild the number in place. Because these variables occupy a constant amount of memory regardless of the magnitude of the input integer, no auxiliary data structures scaling with the input are created. As the number of digits in the input grows, the extra memory required remains entirely fixed. Therefore, the auxiliary space complexity is constant, denoted as O(1).

Optimal Solution

Approach

The optimal strategy for reversing a whole number is to repeatedly peel off the very last digit from the original number and attach it to the end of our new reversed number. We do this by working from right to left, moving digits over to make room as we build the reversed result piece by piece.

Here's how the algorithm would work step-by-step:

  1. Keep track of a new reversed number, starting at zero.
  2. Look at the very last digit of the starting number.
  3. Take that last digit and attach it to the end of our new reversed number, making sure to shift any previously attached digits over to the left to make room.
  4. Remove that last digit from the starting number so we do not look at it again.
  5. Repeat this process of grabbing the last digit, shifting the new number, and shrinking the starting number until no digits are left.
  6. Before adding any digit, check to make sure the new number will not grow too large to fit safely within normal numerical limits.
  7. If the number becomes too large during this process, safely stop and report a limit violation instead of finishing the reversal.

Code Implementation

class Solution:
    def reverse(self, original_integer: int) -> int:
        reversed_number = 0
        
        if original_integer < 0:
            sign_multiplier = -1
            remaining_digits = -original_integer
        else:
            sign_multiplier = 1
            remaining_digits = original_integer
            
        max_limit = 2**31 - 1
        min_limit = -2**31
        
        while remaining_digits != 0:
            last_digit = remaining_digits % 10
            remaining_digits //= 10
            
            # Prevent integer overflow before applying the new digit to the accumulator.
            if reversed_number > (max_limit - last_digit) // 10:
                return 0
                
            reversed_number = reversed_number * 10 + last_digit
            
        final_result = reversed_number * sign_multiplier
        
        # Ensure the final signed integer remains within standard 32-bit bounds.
        if final_result < min_limit or final_result > max_limit:
            return 0
            
        return final_result

Big(O) Analysis

Time Complexity
O(log n) – The input size n is the value of the integer itself, and the cost is driven by the number of decimal digits it contains. In each iteration of the loop, we divide the starting number by 10 by peeling off its last digit. The number of digits in a base-10 integer n is proportional to the logarithm base 10 of n, meaning the loop runs roughly log10(n) times. Since the work done inside the loop is constant time, the total operations scale with the number of digits, which simplifies to O(log n).
Space Complexity
O(1) – The algorithm only requires a few primitive integer variables to keep track of the new reversed number and the remaining digits of the input. No auxiliary data structures, temporary lists, or recursion stack frames are allocated during the process. Because the amount of extra memory remains constant regardless of the magnitude of the input integer, the auxiliary space complexity is strictly constant.

Edge Cases

Signed 32-bit integer overflow during reversal
How to Handle:
We check if the accumulated result will exceed the integer limits before multiplying by ten and adding the next digit.
Negative signed integers
How to Handle:
The modulo and division operators preserve the negative sign in languages like C++ and Java, naturally handling negative numbers.
Input integer is exactly zero
How to Handle:
The algorithm enters the loop once, pops zero, and correctly returns zero without any issues.
Numbers ending in zero such as 120
How to Handle:
The trailing zero becomes a leading zero during math operations and is naturally dropped, resulting in 21.
Boundary values like INT_MAX or INT_MIN
How to Handle:
Reversing these extreme values causes an immediate overflow, which triggers our overflow check and returns zero.
Single-digit integers
How to Handle:
The loop runs once and returns the exact same digit since single-digit numbers are already reversed.
0/2 completed