diff --git a/src/lib.rs b/src/lib.rs index c50afde6..d1ea9fec 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1473,6 +1473,7 @@ pub mod problem_1926_nearest_exit_from_entrance_in_maze; pub mod problem_1929_concatenation_of_array; pub mod problem_1935_maximum_number_of_words_you_can_type; pub mod problem_1941_check_if_all_characters_have_equal_number_of_occurrences; +pub mod problem_1945_sum_of_digits_of_string_after_convert; #[cfg(test)] mod test_utilities; diff --git a/src/problem_1945_sum_of_digits_of_string_after_convert/iterative.rs b/src/problem_1945_sum_of_digits_of_string_after_convert/iterative.rs new file mode 100644 index 00000000..3931867a --- /dev/null +++ b/src/problem_1945_sum_of_digits_of_string_after_convert/iterative.rs @@ -0,0 +1,49 @@ +pub struct Solution; + +// ------------------------------------------------------ snip ------------------------------------------------------ // + +impl Solution { + pub fn get_lucky(s: String, k: i32) -> i32 { + let k = k as u32; + let mut value = 0; + + // Convert and transform. + + for c in s.into_bytes() { + let c = c - (b'a' - 1); + + value += u16::from(c / 10 + c % 10); + } + + // Transform. + + for _ in 1..k { + let mut temp = 0; + + while value != 0 { + temp += value % 10; + value /= 10; + } + + value = temp; + } + + i32::from(value) + } +} + +// ------------------------------------------------------ snip ------------------------------------------------------ // + +impl super::Solution for Solution { + fn get_lucky(s: String, k: i32) -> i32 { + Self::get_lucky(s, k) + } +} + +#[cfg(test)] +mod tests { + #[test] + fn test_solution() { + super::super::tests::run::(); + } +} diff --git a/src/problem_1945_sum_of_digits_of_string_after_convert/mod.rs b/src/problem_1945_sum_of_digits_of_string_after_convert/mod.rs new file mode 100644 index 00000000..d5afdef5 --- /dev/null +++ b/src/problem_1945_sum_of_digits_of_string_after_convert/mod.rs @@ -0,0 +1,18 @@ +pub mod iterative; + +pub trait Solution { + fn get_lucky(s: String, k: i32) -> i32; +} + +#[cfg(test)] +mod tests { + use super::Solution; + + pub fn run() { + let test_cases = [(("iiii", 1), 36), (("leetcode", 2), 6), (("zbax", 2), 8)]; + + for ((s, k), expected) in test_cases { + assert_eq!(S::get_lucky(s.to_string(), k), expected); + } + } +}