Reverse Integer solution and explanation
9 more videos on this problem
Reverse Integer - Bit Manipulation - Leetcode 7 - PythonNeetCode · 13:12 · 132K views
LeetCode Reverse Integer Solution Explained - JavaNick White · 6:20 · 78K views
Reverse Integer | LeetCode problem 7Technosage · 7:00 · 45K views
Leetcode #7 - Reverse Integer | PythonnETSETOS · 9:35 · 22K views
Leetcode Solution - 7.0 Reverse Integer | JavascriptThinkFWD · 10:18 · 15K views
LeetCode 7: Reverse IntegerAbstracted Away · 11:02 · 8K views
Reverse Integer Python Solution - LeetCode #7Professor Oakes · 4:22 · 3K views
REVERSE INTEGER | LEETCODE 7 | PYTHON MATH SOLUTIONCracking FAANG · 8:28 · 2K views
REVERSE INTEGER C++ | SOLVING FAANG CODING INTERVIEW | LEETCODE QUESTION 7CS Ninja · 6:04 · 1K views
Reverse Integer | LeetCode 7 | Top Array Interview Question | Geekster Java DSA | Amazon Google MetaGeekster · 4:47 · 1K views
The 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 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
Approach overview
Problem Overview: Reverse the digits of a signed 32-bit integer x. If reversing the digits causes the value to go outside the 32-bit signed integer range [-2^31, 2^31 - 1], return 0. Negative numbers must preserve their sign after reversal.
Approach 1: Iterative Division and Modulus (Time: O(d), Space: O(1))
This approach processes the integer digit by digit using arithmetic operations. Repeatedly extract the last digit using x % 10, append it to a new number using rev = rev * 10 + digit, and remove the last digit from the original number with integer division x //= 10. The key challenge is detecting overflow before it happens. You check whether rev will exceed the 32-bit boundary before multiplying by 10. This solution uses constant space and avoids converting the number to a string, making it the standard arithmetic solution expected in interviews involving math and integer manipulation.
Approach 2: String Conversion and Manipulation (Time: O(d), Space: O(d))
This approach converts the integer to a string, reverses the characters, and converts the result back to an integer. Handle the negative sign separately: store it, reverse the remaining digits, then reapply the sign. After conversion, verify the result still falls within the 32-bit signed integer range. This method is simpler to implement and easier to reason about, but it uses extra memory for the string and relies on built-in string operations from languages such as Python or JavaScript. It demonstrates basic manipulation of strings rather than pure math operations.
Recommended for interviews: The iterative division and modulus approach is the one interviewers expect. It shows you understand integer digit extraction, overflow detection, and constant-space arithmetic. The string method is acceptable for quick implementations, but the arithmetic solution demonstrates stronger algorithmic control over numeric operations.
Approach 1: Iterative Division and Modulus
This method involves extracting digits one at a time from the integer using modulus and division operations. By repeatedly taking the last digit of the number, you can construct the reversed integer. However, special care must be taken to handle the overflow condition, as reversing an integer can potentially produce a value beyond the 32-bit signed integer limit.
def reverse(x):
result = 0
while x != 0:
pop = x % 10
if x < 0 and pop > 0:
pop -= 10
x = (x - pop) // 10
if result > 214748364 or (result == 214748364 and pop > 7): return 0
if result < -214748365 or (result == -214748365 and pop < -8): return 0
result = result * 10 + pop
return result
x = -123
print(reverse(x))public class ReverseInteger {
public static int reverse(int x) {
int result = 0;
while (x != 0) {
int pop = x % 10;
x /= 10;
if (result > Integer.MAX_VALUE/10 || (result == Integer.MAX_VALUE / 10 && pop > 7)) return 0;
if (result < Integer.MIN_VALUE/10 || (result == Integer.MIN_VALUE / 10 && pop < -8)) return 0;
result = result * 10 + pop;
}
return result;
}
public static void main(String[] args) {
int x = 120;
System.out.println(reverse(x));
}
}#include <iostream>
using namespace std;
int reverse(int x) {
int result = 0;
while (x != 0) {
int pop = x % 10;
x /= 10;
if (result > INT_MAX / 10 || (result == INT_MAX / 10 && pop > 7)) return 0;
if (result < INT_MIN / 10 || (result == INT_MIN / 10 && pop < -8)) return 0;
result = result * 10 + pop;
}
return result;
}
int main() {
int x = -123;
cout << reverse(x);
return 0;
}function reverse(x) {
let result = 0;
while (x !== 0) {
let pop = x % 10;
x = (x / 10) | 0;
if (result > 214748364 || (result === 214748364 && pop > 7)) return 0;
if (result < -214748364 || (result === -214748364 && pop < -8)) return 0;
result = result * 10 + pop;
}
return result;
}
console.log(reverse(-120));#include <stdio.h>
#include <limits.h>
int reverse(int x) {
int result = 0;
while (x != 0) {
int pop = x % 10;
x /= 10;
if (result > INT_MAX / 10 || (result == INT_MAX / 10 && pop > 7)) return 0;
if (result < INT_MIN / 10 || (result == INT_MIN / 10 && pop < -8)) return 0;
result = result * 10 + pop;
}
return result;
}
int main() {
int x = 123;
printf("%d", reverse(x));
return 0;
}using System;
class ReverseInteger {
public static int Reverse(int x) {
int result = 0;
while (x != 0) {
int pop = x % 10;
x /= 10;
if (result > int.MaxValue / 10 || (result == int.MaxValue / 10 && pop > 7)) return 0;
if (result < int.MinValue / 10 || (result == int.MinValue / 10 && pop < -8)) return 0;
result = result * 10 + pop;
}
return result;
}
static void Main(string[] args) {
int x = 123;
Console.WriteLine(Reverse(x));
}
}In Python, integer overflow isn't a concern like in other languages, but here a similar approach to digit extraction and accumulation is used, with overflow logic adapted from a 32-bit perspective.
Time Complexity: O(log10(x)).
Space Complexity: O(1).
Approach 2: String Conversion and Manipulation
In this approach, the integer is first converted to a string representation, reversed as a string, and then converted back to an integer. This method mitigates overflow issues by checking the integer post-conversion if it falls within the valid range.
def reverse(x):
sign = -1 if x < 0 else 1
x *= sign
reversed_x = int(str(x)[::-1])
if reversed_x > 2**31 - 1:
return 0
return sign * reversed_x
x = 123
print(reverse(x))function reverse(x) {
const sign = Math.sign(x);
x = Math.abs(x);
const reversed = parseInt(x.toString().split('').reverse().join(''));
if (reversed > Math.pow(2, 31) - 1) return 0;
return reversed * sign;
}
console.log(reverse(-123));This Python solution converts the integer x to a string, reverses it, and then converts it back to an integer. The sign is preserved and checked for overflow before returning the result.
Time Complexity: O(n) where n is the number of digits in x.
Space Complexity: O(n) due to the use of the string to store digits temporarily.
Approach 3: Mathematics
Let's denote mi and mx as -2^{31} and 2^{31} - 1 respectively, then the reverse result of x, ans, needs to satisfy mi \le ans \le mx.
We can continuously take the remainder of x to get the last digit y of x, and add y to the end of ans. Before adding y, we need to check if ans overflows. That is, check whether ans times 10 + y is within the range [mi, mx].
If x \gt 0, it needs to satisfy ans times 10 + y leq mx, that is, ans times 10 + y leq \left \lfloor \frac{mx}{10} \right \rfloor times 10 + 7. Rearranging gives (ans - \left \lfloor \frac{mx}{10} \right \rfloor) times 10 leq 7 - y.
Next, we discuss the conditions for the inequality to hold:
- When
ans \lt \left \lfloor \frac{mx}{10} \right \rfloor, the inequality obviously holds; - When
ans = \left \lfloor \frac{mx}{10} \right \rfloor, the necessary and sufficient condition for the inequality to hold isy leq 7. Ifans = \left \lfloor \frac{mx}{10} \right \rfloorand we can still add numbers, it means that the number is at the highest digit, that is,ymust not exceed2, therefore, the inequality must hold; - When
ans \gt \left \lfloor \frac{mx}{10} \right \rfloor, the inequality obviously does not hold.
In summary, when x \gt 0, the necessary and sufficient condition for the inequality to hold is ans leq \left \lfloor \frac{mx}{10} \right \rfloor.
Similarly, when x \lt 0, the necessary and sufficient condition for the inequality to hold is ans geq \left \lfloor \frac{mi}{10} \right \rfloor.
Therefore, we can check whether ans overflows by checking whether ans is within the range [\left \lfloor \frac{mi}{10} \right \rfloor, \left \lfloor \frac{mx}{10} \right \rfloor]. If it overflows, return 0. Otherwise, add y to the end of ans, and then remove the last digit of x, that is, x \gets \left \lfloor \frac{x}{10} \right \rfloor.
The time complexity is O(log |x|), where |x| is the absolute value of x. The space complexity is O(1).
func reverse(x int) (ans int) {
for ; x != 0; x /= 10 {
if ans < math.MinInt32/10 || ans > math.MaxInt32/10 {
return 0
}
ans = ans*10 + x%10
}
return
}impl Solution {
pub fn reverse(mut x: i32) -> i32 {
let is_minus = x < 0;
match x
.abs()
.to_string()
.chars()
.rev()
.collect::<String>()
.parse::<i32>()
{
Ok(x) => x * (if is_minus { -1 } else { 1 }),
Err(_) => 0,
}
}
}class Solution {
/**
* @param int $x
* @return int
*/
function reverse($x) {
$isNegative = $x < 0;
$x = abs($x);
$reversed = 0;
while ($x > 0) {
$reversed = $reversed * 10 + ($x % 10);
$x = (int) ($x / 10);
}
if ($isNegative) {
$reversed *= -1;
}
if ($reversed < -pow(2, 31) || $reversed > pow(2, 31) - 1) {
return 0;
}
return $reversed;
}
}Complexity comparison
| Approach | Complexity |
|---|---|
| Iterative Division and Modulus | Time Complexity: O(log10(x)). |
| String Conversion and Manipulation | Time Complexity: O(n) where n is the number of digits in x. |
| Mathematics | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Iterative Division and Modulus | O(d) | O(1) | Preferred interview solution. Uses arithmetic operations and handles overflow explicitly. |
| String Conversion and Manipulation | O(d) | O(d) | Quick implementation when readability matters more than strict constant space. |
Frequently asked questions
Is Reverse Integer easy or hard?
Reverse Integer is generally classified as a medium problem because of the overflow constraint. Reversing digits itself is simple, but correctly detecting overflow without using larger numeric types requires careful boundary checks.
Reverse Integer Python/Java solution
In Python or Java, the arithmetic solution repeatedly extracts digits using modulus and builds the reversed number with multiplication by 10. Java implementations must explicitly check 32-bit overflow using Integer.MAX_VALUE and Integer.MIN_VALUE. Python still needs manual boundary checks to match the problem constraints.
How to solve Reverse Integer in O(n)?
Treat n as the number of digits in the integer. Repeatedly extract digits using modulus, build the reversed number using multiplication by 10, and check for overflow before each update. The loop runs once per digit, giving O(n) time and O(1) extra space.
What is the best approach for Reverse Integer?
The best approach uses iterative division and modulus. Extract the last digit with x % 10, append it to the reversed number using rev = rev * 10 + digit, and shrink the original number with integer division. Add overflow checks before multiplying by 10. This runs in O(d) time and O(1) space where d is the number of digits.
Is Reverse Integer asked at Google/Amazon/Meta?
Reverse Integer is a common screening-level problem used by companies like Amazon, Google, and Meta to test understanding of integer manipulation, overflow handling, and basic algorithmic reasoning. Variants appear in phone screens and coding assessments.
What data structure is used in Reverse Integer?
The optimal solution does not require any data structure. It relies purely on arithmetic operations such as modulus and integer division. The alternative implementation uses strings for digit reversal, which introduces extra memory usage.
What is the time complexity of Reverse Integer?
The time complexity is O(d), where d is the number of digits in the integer. Each iteration processes one digit using modulus and division. Since a 32-bit integer has at most 10 digits, the operation effectively runs in constant time.
