← 中文资源

简体中文版本

数字数组整体加一

从最低位向左遍历逐位处理进位:小于 9 的位直接加一并返回,等于 9 的位归零后继续进位;全为 9 时在最前面补一个 1,不会溢出。

阅读英文原文

实现说明

主线是函数 plus_one、main的调用过程。 重复被限制在 for d in out.iter_mut().rev() 里——其余代码按顺序各跑一遍。

使用要点

  • 运行整个文件:main 会依次驱动 plus_one。

常见问题

「数字数组整体加一」这个示例怎么运行?

直接执行即可——程序只依赖运行时自身。

入口签名:fn plus_one(digits: &[u8]) -> Option<Vec<u8>>

核心语句

return Some(out);

代码示例

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));
    }
}