Mastering the Reverse Integer Algorithm for Interviews
Written on
Chapter 1: Understanding the Problem
In the realm of technical interviews, the Reverse Integer challenge is a common question. The task is straightforward: given a signed 32-bit integer x, your goal is to return x with its digits reversed. However, if the reversal results in a value that exceeds the signed 32-bit integer range of [-2^31, 2^31 - 1], you should return 0. Additionally, it's essential to note that the environment does not permit the use of 64-bit integers (neither signed nor unsigned).
Example Cases:
Input: x = 123
Output: 321
Input: x = -123
Output: -321
Input: x = 120
Output: 21
Constraints:
- The integer x must satisfy: -2^31 <= x <= 2^31 - 1
Optimized Approach
To reverse the integer effectively, we can construct the reversed number digit by digit while ensuring we don’t encounter overflow conditions.
Section 1.1: Algorithm Overview
Reversing an integer can be approached similarly to reversing a string. The idea is to "pop" the last digit from x and "push" it to a new integer rev. Ultimately, rev will hold the reversed value of x.
To accomplish this without using an auxiliary stack or array, we can employ basic arithmetic operations.
Subsection 1.1.1: Implementation in C++
Here’s a C++ solution for the Reverse Integer problem:
class Solution {
public:
int reverse(int x) {
int rev = 0;
while (x != 0) {
int pop = x % 10;
x /= 10;
if (rev > INT_MAX / 10 || (rev == INT_MAX / 10 && pop > 7)) return 0;
if (rev < INT_MIN / 10 || (rev == INT_MIN / 10 && pop < -8)) return 0;
rev = rev * 10 + pop;
}
return rev;
}
};
Section 1.2: Implementation in Java
Here's how you can implement the same logic in Java:
class Solution {
public int reverse(int x) {
int rev = 0;
while (x != 0) {
int pop = x % 10;
x /= 10;
if (rev > Integer.MAX_VALUE / 10 || (rev == Integer.MAX_VALUE / 10 && pop > 7)) return 0;
if (rev < Integer.MIN_VALUE / 10 || (rev == Integer.MIN_VALUE / 10 && pop < -8)) return 0;
rev = rev * 10 + pop;
}
return rev;
}
}
Chapter 2: Python Solution
For those who prefer Python, here's a simple implementation:
class Solution:
def reverse(self, x: int) -> int:
if x > 0:
ans = int(str(x)[::-1])else:
ans = int(str(x * -1)[::-1]) * -1
mi = 2 ** 31 * (-1)
ma = 2 ** 31 - 1
if ans > ma or ans < mi:
return 0return ans
The first video titled "GOOGLE Coding Interview Question - Reverse Integer | LeetCode" provides a detailed explanation of the Reverse Integer problem and demonstrates how to solve it effectively.
Another insightful video titled "[Interview Question] Reverse Integer (with Binary Number Explanation)" delves deeper into the concept, offering a unique perspective on this coding challenge.
Stay tuned for more engaging interview questions and coding challenges, as I continue to share valuable insights from my experience as a senior software engineer at MANNG.