Algo-Sim › Math & Geometry
Reverse Integer
Medium · Math & Geometry · step through it in Java, Python and C++ on your own input
Reverse the digits of a 32-bit integer, returning 0 on overflow. Pop with % 10, push with × 10, and check the limit before every multiply.
Problem
Given a signed 32-bit integer x, return the integer formed by its digits in reverse order, keeping the sign. If that value falls outside [−2³¹, 2³¹ − 1], return 0. Assume the environment cannot hold 64-bit integers.
Constraints
- −2³¹ ≤ x ≤ 2³¹ − 1
- No 64-bit types: detect overflow before it happens
Edge cases to test
- A result that overflows:
0 - Trailing zeros:
120→21 - Negative numbers
Follow-up questions
- How do you check overflow with only 32-bit ints?
- Before
rev × 10 + d, checkrev > MAX / 10orrev == MAX / 10 && d > 7(and the mirror for negatives). - How does Java’s
%handle negatives? - It keeps the sign of the dividend, so digits of a negative number are negative and the same loop works.
Solution
Java
public int reverse(int x) {
int rev = 0;
while (x != 0) {
int digit = x % 10;
x /= 10;
if (rev > Integer.MAX_VALUE / 10 || (rev == Integer.MAX_VALUE / 10 && digit > 7)) {
return 0;
}
if (rev < Integer.MIN_VALUE / 10 || (rev == Integer.MIN_VALUE / 10 && digit < -8)) {
return 0;
}
rev = rev * 10 + digit;
}
return rev;
}Python
def reverse(x):
# Python ints never overflow, so check against 32-bit limits by hand.
limit = (2**31 - 1) // 10
rev = 0
while x != 0:
digit = x % 10 if x > 0 else -(-x % 10)
x = (x - digit) // 10
if rev > limit or (rev == limit and digit > 7):
return 0
if rev < -limit or (rev == -limit and digit < -8):
return 0
rev = rev * 10 + digit
return revC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int reverse(int x) {
int rev = 0;
while (x != 0) {
int digit = x % 10;
x /= 10;
if (rev > INT_MAX / 10 || (rev == INT_MAX / 10 && digit > 7)) {
return 0;
}
if (rev < INT_MIN / 10 || (rev == INT_MIN / 10 && digit < -8)) {
return 0;
}
rev = rev * 10 + digit;
}
return rev;
}
};
More Math & Geometry problems
- Plus One (Easy)
- Happy Number (Easy)
- GCD and LCM (Euclid) (Easy)
- Count Primes (Sieve of Eratosthenes) (Medium)
- Pow(x, n) (Medium)
- Count Good Numbers (mod 1e9+7) (Medium)
- Multiply Strings (Medium)
- String to Integer (atoi) (Medium)
- Detect Squares (Medium)
- Random Pick with Weight (Medium)
- Shuffle an Array (Medium)
- Linked List Random Node (Medium)
- Pascal's Triangle (Easy)
- nCr mod p (Medium)
- Max Points on a Line (Hard)