#7
Medium Algorithms Reverse integer
Math
31.5% acceptance
Jan 12, 2026
15362
13990
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).
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn reverse(x: i32) -> i32 {
let mut num = x;
let mut result = 0i32;
while num != 0 {
let digit = num % 10;
num /= 10;
// Check for overflow before multiplying by 10
// If result > i32::MAX / 10, then result * 10 will overflow
// If result < i32::MIN / 10, then result * 10 will underflow
if result > i32::MAX / 10 || result < i32::MIN / 10 {
return 0;
}
// Check for overflow when adding the digit
// When result == i32::MAX / 10, we need to ensure that adding digit won't overflow
// i32::MAX = 2147483647, so i32::MAX / 10 = 214748364
// When result == 214748364, digit must be <= 7 to not overflow
// Similarly for negative: i32::MIN = -2147483648, i32::MIN / 10 = -214748364
// When result == -214748364, digit must be >= -8 to not underflow
if result == i32::MAX / 10 && digit > 7 {
return 0;
}
if result == i32::MIN / 10 && digit < -8 {
return 0;
}
result = result * 10 + digit;
}
result
}
}