Skip to content

Commit

Permalink
Add problem 1945: Sum of Digits of String After Convert
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Nov 10, 2023
1 parent b0ac601 commit 7835092
Show file tree
Hide file tree
Showing 3 changed files with 68 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Original file line number Diff line number Diff line change
@@ -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::<super::Solution>();
}
}
18 changes: 18 additions & 0 deletions src/problem_1945_sum_of_digits_of_string_after_convert/mod.rs
Original file line number Diff line number Diff line change
@@ -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<S: Solution>() {
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);
}
}
}

0 comments on commit 7835092

Please sign in to comment.