1
Fork 0
leetcode/source/plus_one/mod.rs

34 lines
1.0 KiB
Rust
Raw Permalink Normal View History

2022-04-07 15:59:57 +00:00
pub fn plus_one(digits: Vec<i32>) -> Vec<i32> {
// Keep track of when to carry for the next digit.
let mut carry = false;
// Reverse the digits so they're from least to most significant.
let mut digits = digits.into_iter().rev();
// Create a vector to store the incremented digits.
let mut incremented = vec![];
2022-04-08 21:00:38 +00:00
for digit in digits.by_ref() {
2022-04-07 15:59:57 +00:00
if digit == 9 {
// When the current digit is 9 save 0 and keep going through the digits.
incremented.push(0);
carry = true;
} else {
// When the digit isn't 9, increment it and save it, set carry to false
// and break the loop early.
incremented.push(digit + 1);
carry = false;
break;
}
}
// If the last digit was a 9 we have to add an extra 1, for example:
// [9] turns into [0] and then here we make it [0, 1].
if carry {
incremented.push(1);
}
// Then reverse both iterators so they're in the correct order and chain them.
digits.rev().chain(incremented.into_iter().rev()).collect()
}