Leetcode in Rust: #7 - Reverse Integer

Written by Katrina Ellison Geltman on Thu 09 October 2025.

https://leetcode.com/problems/reverse-integer/description/

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).

pub fn reverse(x: i32) -> i32 {
    let mut input = x;
    let mut output = 0;
    let mut last_digit;
    while input.abs() > 0 {
        last_digit = input % 10;
        input = input / 10;
        if output > i32::MAX / 10
            || output == i32::MAX / 10 && last_digit > 7
            || output < i32::MIN / 10
            || output == i32::MIN / 10 && last_digit < -8
        {
            return 0;
        }
        output = output * 10 + last_digit;
    }
    output
}

Why the last_digit > 7 and last_digit < -8 cases? This is because i32::MAX = 2147483647, so 2147483648 and 2147483649 will cause an overflow, and i32::MIN = -2147483648, so -2147483649 will cause an underflow.

Want to become a better programmer? Join the Recurse Center!