Plus One Increment For Digit Array

Walk digits from the least significant end carrying the increment; when every digit rolls over, prepend one instead of overflowing.

RustData Integrity

Code

rustsnippet
21 lines
fn plus_one(digits: &[u8]) -> Option<Vec<u8>> {
    // Walk from the least significant digit, carrying the increment
    let mut out = digits.to_vec();
    for d in out.iter_mut().rev() {
        if *d < 9 {
            *d += 1;
            return Some(out);
        }
        *d = 0; // carry: digit rolls over to 0
    }
    // All nines: prepend one extra leading digit
    out.insert(0, 1);
    Some(out)
}

fn main() {
    let cases: [&[u8]; 4] = [&[1, 2, 3], &[9], &[9, 9, 9], &[]];
    for case in cases {
        println!("{case:?} -> {:?}", plus_one(case));
    }
}

Behavior at a glance

Plus One Increment For Digit Array keeps everything in the functions plus_one and main.

A single loop drives the file — for d in out.iter_mut().rev().

Caveats

  • Runs on the standard library alone; nothing to install.

Applying it

What the code exposes: fn plus_one(digits: &[u8]) -> Option<Vec<u8>>

Launch the file; main takes over and steps through plus_one.

Statements that matter

return Some(out);

Interactive Tools for This Topic

FAQ

How do you run Plus One Increment For Digit Array?
Run it as a complete program — compile or interpret the file directly; there is nothing to install first.