I folded ten nines into an i32 and the release build handed me back a wrong number, without complaining.

The tempting version of this problem folds the digit array into an integer, adds one, and folds the result back into an array. I wrote that version as a separate experiment to see what it costs, and ran it on ten nines. Here is the experiment:

let digits: Vec<i32> = vec![9; 10]; // 9999999999
let n = digits.iter().fold(0i32, |acc, d| acc * 10 + d);

In debug:

attempt to multiply with overflow

In release:

folded = 1410065407

9999999999 does not fit in an i32, so the release build wrapped it: 9999999999 minus two times 4294967296 is 1410065407. No panic, no diagnostic, no clue that the number is wrong. The problem allows 100 digits. A hundred nines is a number that no fixed-width integer type in the language can hold.

The repo’s solution never forms the number at all. Here it is:

pub fn plus_one(digits: Vec<i32>) -> Vec<i32> {
    let mut digits = digits;

    // For every digit, go in reverse order
    for i in (0..digits.len()).rev() {
        // if the least remaining digit at i is less than 9
        if digits[i] < 9 {
            digits[i] += 1;
            return digits;
        }
        // Digit is 9, then it becomes zero and the carry is 1
        digits[i] = 0;
    }

    let mut result = vec![1];
    result.append(&mut digits);
    result
}

Every value in that function is a single digit.

The i32 type is being used to hold numbers from 0 to 9, and the type is never asked to hold anything else. Overflow does not get prevented here; it gets made structurally impossible.

The guard is doing all the work

The only arithmetic on a digit is digits[i] += 1, and it sits behind if digits[i] < 9. A digit that reaches the increment is at most 8, so the result is at most 9.

There is no code path that produces a value outside 0..=9, and therefore no code path that can overflow.

Compare that to the fold above, where the same i32 type is asked to hold 9999999999 and quietly fails. The difference is not care. The difference is that one of them never asks.

Rust would have caught the fold. The attempt to multiply with overflow panic happens on the first run, in the debug profile, before the answer is ever wrong. The interesting part is not that the compiler caught it. The interesting part is that the compiler did not catch the digit version, because the digit version cannot be wrong in that way. The guard makes the failure unreachable rather than detectable.

The carry is the loop control

There is no carry variable in the function. The carry is implicit in the loop control: the fact that the loop is still running means every digit to the right of i was a nine and has already been turned into a zero.

That is what the reverse range is doing. for i in (0..digits.len()).rev() walks the digits from the least significant to the most significant, and it stops the moment a digit can absorb the increment.

Two details are worth naming. The range is built as 0..digits.len() and then reversed, rather than written as a descending range, because digits.len() is read once at the start and the reversed iterator cannot underflow. And digits.len() is evaluated before the loop starts, so mutating digits inside the loop cannot invalidate the iteration.

The shadow is doing two things

let mut digits = digits; looks like noise. It is doing two things.

First, it is a move, not a copy. Vec<i32> is not Copy, so the original binding is consumed and the new one takes ownership of the same buffer. I checked by comparing the pointer on either side of the shadow: the buffer address is identical before and after, and the capacity does not move. No allocation, no clone.

Second, it is what makes the function body compile at all. A function parameter is an immutable binding unless you say otherwise, and the LeetCode harness fixes the signature to digits: Vec<i32>. Remove the shadow and the body fails to compile with one error and three notes:

error[E0596]: cannot borrow `digits` as mutable, as it is not declared as mutable

The compiler points at three places that need a mutable binding: digits[i] += 1, digits[i] = 0, and result.append(&mut digits). Its own suggestion is to change the signature to mut digits: Vec<i32>.

The compiler suggests mut digits: Vec<i32> in the signature, which would work and would make the shadow unnecessary. But the signature is not mine to change, so the shadow is the honest way to get mutability while keeping the given shape. Clippy does not flag it either; I enabled redundant_locals explicitly and it stayed quiet, because the shadow is not redundant in the program as written.

The carry out of the top

The carry out of the top digit is the only case that changes the length of the array, and it is handled by constructing a new one:

let mut result = vec![1];
result.append(&mut digits);
result

append takes &mut Vec<i32> and moves every element out of the source, leaving it empty. I confirmed that: after the call the source is []. The digits left behind are all zeros, since the loop only reaches this line by turning every digit into a zero, so the result is a leading one followed by the original number of zeros. [9, 9, 9] becomes [1, 0, 0, 0].

There is one small cost here. vec![1] allocates capacity for exactly one element, and appending three more forces a reallocation, taking capacity from 1 to 4. Vec::with_capacity(digits.len() + 1) would avoid it. That is the one place this solution allocates more than once, and it is a fair thing to fix, but it is a different problem from the one this file is about.

The digits are the source of truth

The reason this solution is safe is not that it checks the arithmetic. It is that it chose a representation where the arithmetic cannot be wrong. The digits are the source of truth, the carry lives in the control flow, and the integer that does not fit in a machine word never exists anywhere in the program.

The alternative was always available and always looked reasonable. It was one fold away from returning a wrapped number with total confidence.

The rule I keep from this: if the problem says the number might be long, do not build it. Keep the digits as digits and let the control flow carry. And when I do fold a long number into a machine integer just to see what it costs, I run it in debug first, where the multiply says out loud that it overflowed.


Next: The Stack That Refused to Pop