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

34 lines
1.0 KiB
Rust

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![];
for digit in digits.by_ref() {
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()
}