In a release build, reverse(1534236469) returns 1056389759. The problem says the answer is zero for that input.

I wrote an overflow guard into the reverse-integer solution to stop the reversed number from leaving i32. It has never fired once. I instrumented the guard and counted every evaluation of its condition across 3,000,169 inputs, 28,449,084 guard checks in total. The positive branch returned zero times. The negative branch returned zero times.

The function it was protecting is the only thing in the crate that can overflow.

Here is the whole function, as it shipped:

pub fn reverse(x: i32) -> i32 {
    // Create a mutable input
    let mut num = x;
    // the reversed integer
    let mut reversed: i32 = 0;
    // While the number is not equal to 0
    while num != 0 {
        let digit = num % 10; // get the last digit
        // Check boundaries
        // if the reversed integer is larger than the maximum number
        // as a digit
        // and reversed is equal to the max number and
        // the new digit is larger than the maximum addition
        if reversed > i32::MAX / 10 && (reversed == i32::MAX && digit > 7) {
            return 0;
        }
        // if the reversed number is smaller than the minimum decimal
        // value and
        // the reversed integer is equal to the absolute minimum
        // and the digit will shrink the number further, return 0
        if reversed < i32::MIN / 10 && (reversed == i32::MIN && digit < -8) {
            return 0;
        }
        // Add the reversed integer with the last digit
        reversed = reversed * 10 + digit;
        // Continue shrinking the number
        num /= 10
    }
    reversed
}

Two things are wrong with it. Only one of them changes the answer.

It should have been ||

The intent is the standard one. Before multiplying reversed by ten, check whether the result would leave the range, and if it would, return 0, because the problem says to return 0 when the reversal overflows.

The check has two halves: either reversed is already so large that any digit overflows, or reversed is exactly at the boundary and only some digits overflow.

&& requires both halves. It should be ||. Either half alone is enough to justify returning 0.

A comparison that can never be true

Look at the right-hand side of the first guard: reversed == i32::MAX. For that to be true, reversed would have to hold exactly 2147483647 at the moment the guard is evaluated.

The guard runs at the top of the loop, before the multiply. At that point reversed holds the digits extracted so far. An i32 has at most ten decimal digits, so at the guard check reversed has at most nine, and its magnitude is at most 999999999.

i32::MAX is 2147483647. Ten digits. i32::MIN is -2147483648. Also ten digits.

Neither is reachable at a guard check. Ever, for any i32 input.

Which means the guards are not merely narrow. They are unconditionally false. && with a right operand that is always false is always false, so the function has no overflow protection at all, and the comments above it describe a protection that does not exist.

The operator is the one that matters

The operator is the one that changes the answer. I changed && to || on its own and left the comparisons alone, and that was enough: all four inputs in the table below started returning 0 in both profiles.

The reachable half of each guard is the half that matters, because reversed > i32::MAX / 10 and reversed < i32::MIN / 10 are exactly the conditions under which the multiply itself is about to leave the range.

The comparison is the one that is wrong but harmless. i32::MAX / 10 is 214748364, nine digits, and reachable at a guard check. i32::MAX is ten digits and never reachable. Written correctly, the guard reads:

if reversed > i32::MAX / 10 || (reversed == i32::MAX / 10 && digit > 7) {
    return 0;
}
if reversed < i32::MIN / 10 || (reversed == i32::MIN / 10 && digit < -8) {
    return 0;
}

That is the boundary case the first disjunct cannot see. reversed is exactly 214748364, multiplying by ten gives 2147483640 which is still inside i32, but adding a digit above 7 pushes it out.

And it is still very hard to reach. Getting reversed to exactly 214748364 takes an input whose last nine digits are 463847412, so a ten-digit input of that shape is d463847412. To stay inside i32 the leading digit d can only be 1 or 2, but the check needs d to be 8 or 9, which puts the input out of range before it can be tested. 1463847412 is the in-range version, and it reverses to 2147483641, which is inside i32, so the guard correctly does not fire.

I instrumented the corrected guard over 5,012,007 inputs and 47,531,512 guard checks, including a sweep of the neighbourhoods around i32::MIN, i32::MAX, and 1463847412. The second disjunct fired zero times.

So the guard was written with two layers and shipped with none. The layer that is syntactically present is the one that does nothing, and the layer that does all the work is the half that never mentions the boundary value.

What each profile does with it

The problem’s constraint is -2^31 <= x <= 2^31 - 1, and the problem also says the environment does not allow storing 64-bit integers, so i64 is not an escape hatch.

Four inputs sit inside the constraint and reverse to something outside it. The correct answer for all four is 0.

inputexpecteddebug buildrelease build
15342364690panic1056389759
-21474836480panic126087180
21474836470panic-1126087180
-15638474120panic2147483645

In debug, every one of them dies on the same line with the same message:

attempt to multiply with overflow

That message is the compiler doing what it was built to do. Overflow checks are on by default in the debug profile, so reversed * 10 is checked at runtime and the check fires.

The panic names the line. It is loud, immediate, and points at the arithmetic.

In release, overflow checks are off and the multiply wraps. The function returns a confident, plausible, wrong number, and nothing logs it. Forever, with no symptom.

The same source and the same input, two different wrongnesses: a crash in one profile and a lie in the other.

The test passes because the inputs are small

The test suite is this:

#[test]
fn test_reverse() {
    for (input, output) in [(123, 321), (-123, -321), (120, 21)] {
        assert_eq!(Solution::reverse(input), output);
    }
}

It passes. I ran it. cargo test reports one passed, zero failed.

It passes because 123, -123, and 120 reverse to three-digit numbers, and reversed never gets past three digits on its way there. The guard is never needed for those inputs, so the guard being broken is invisible.

The suite has no opinion about the one decision that makes this problem interesting, because every input it exercises answers the question before it is asked.

The four inputs in the table are not exotic. 2147483647 is the largest i32 that exists, and it is inside the problem’s stated range. A suite that included it would have failed on the first cargo test run, in debug, with a message pointing straight at the defect.

The version I wrote by hand

Both defects live in the guard above, and I wrote the corrected version myself rather than taking it from the repository.

With that guard, all four inputs return 0 in both the debug and the release profile, and 123, -123, and 120 still return 321, -321, and 21.

I also checked the corrected guard against a reference implementation that computes the reversal in i64 and then range-checks the result. Over 3,800,011 inputs, including sweeps of both ends of the i32 range and of 1463847412, the two agreed on every one.

The problem statement’s third hint suggests something better anyway: checked_mul and checked_add. That does not require reasoning about which value reversed must equal at the boundary. It asks the multiply whether the multiply fits.

I did not take that hint, and the guard I wrote by hand was wrong in a way that only showed up under the right input.

What the guard has to be able to do

A guard is defensive if it can prevent the thing it names. This one names a boundary and cannot detect the crossing. It is not a weak guard or a narrow guard.

It is a comment wearing the costume of a check.

The reason it is dangerous is that it looks like the decision has been made. A reader sees two return 0 branches above the arithmetic and concludes the overflow is handled. The compiler’s own overflow check was the only thing standing between this function and a wrapped answer, and it had no reason to think it was needed, so it went looking for a borrow error and found none.

In debug, the panic is the cheapest possible signal that the guard was supposed to do a job and did not.

In release, the panic does not come, and the function keeps its confidence.

What I take from it: I do not trust a guard I have never watched fire. The input that makes it fire goes into the test suite before I believe the guard.


Next: The Swap That Panicked