From 83519fe16dd0c28a77a6f917569b298d69832525 Mon Sep 17 00:00:00 2001 From: Bauke Date: Thu, 7 Apr 2022 17:59:57 +0200 Subject: [PATCH] Solve plus-one. --- source/lib.rs | 1 + source/plus_one/mod.rs | 43 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+) create mode 100644 source/plus_one/mod.rs diff --git a/source/lib.rs b/source/lib.rs index 5a6e330..be6e190 100644 --- a/source/lib.rs +++ b/source/lib.rs @@ -1,6 +1,7 @@ pub mod implement_strstr; pub mod longest_common_prefix; pub mod palindrome_number; +pub mod plus_one; pub mod reverse_integer; pub mod roman_to_integer; pub mod two_sum; diff --git a/source/plus_one/mod.rs b/source/plus_one/mod.rs new file mode 100644 index 0000000..eda99fe --- /dev/null +++ b/source/plus_one/mod.rs @@ -0,0 +1,43 @@ +pub fn plus_one(digits: Vec) -> Vec { + // 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]); +}