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

44 lines
1.4 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![];
while let Some(digit) = digits.next() {
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()
}
#[test]
fn test_plus_one() {
assert_eq!(plus_one(vec![1, 2, 3]), vec![1, 2, 4]);
assert_eq!(plus_one(vec![4, 3, 2, 5]), vec![4, 3, 2, 6]);
assert_eq!(plus_one(vec![9]), vec![1, 0]);
assert_eq!(plus_one(vec![9, 9]), vec![1, 0, 0]);
assert_eq!(plus_one(vec![7, 9, 8]), vec![7, 9, 9]);
assert_eq!(plus_one(vec![8, 9, 9]), vec![9, 0, 0]);
}