实现说明
主线是函数 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));
}
}