Skip to content

Commit

Permalink
Add problem 2169: Count Operations to Obtain Zero
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Mar 12, 2024
1 parent a9ccf7b commit 2faa3fd
Show file tree
Hide file tree
Showing 3 changed files with 60 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 @@ -1475,6 +1475,7 @@ pub mod problem_2160_minimum_sum_of_four_digit_number_after_splitting_digits;
pub mod problem_2161_partition_array_according_to_given_pivot;
pub mod problem_2165_smallest_value_of_the_rearranged_number;
pub mod problem_2166_design_bitset;
pub mod problem_2169_count_operations_to_obtain_zero;

#[cfg(test)]
mod test_utilities;
41 changes: 41 additions & 0 deletions src/problem_2169_count_operations_to_obtain_zero/mathematical.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
pub struct Solution;

// ------------------------------------------------------ snip ------------------------------------------------------ //

use std::num::NonZeroU32;

impl Solution {
pub fn count_operations(num1: i32, num2: i32) -> i32 {
let num1 = num1 as u32;
let num2 = num2 as u32;
let (mut num1, mut num2) = if num2 < num1 { (num2, num1) } else { (num1, num2) };
let mut result = 0;

while let Some(non_zero_num1) = NonZeroU32::new(num1) {
result += num2 / non_zero_num1;

let new_num1 = num2 % non_zero_num1;

num2 = num1;
num1 = new_num1;
}

result as _
}
}

// ------------------------------------------------------ snip ------------------------------------------------------ //

impl super::Solution for Solution {
fn count_operations(num1: i32, num2: i32) -> i32 {
Self::count_operations(num1, num2)
}
}

#[cfg(test)]
mod tests {
#[test]
fn test_solution() {
super::super::tests::run::<super::Solution>();
}
}
18 changes: 18 additions & 0 deletions src/problem_2169_count_operations_to_obtain_zero/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
pub mod mathematical;

pub trait Solution {
fn count_operations(num1: i32, num2: i32) -> i32;
}

#[cfg(test)]
mod tests {
use super::Solution;

pub fn run<S: Solution>() {
let test_cases = [((2, 3), 3), ((10, 10), 1), ((79, 68), 14)];

for ((num1, num2), expected) in test_cases {
assert_eq!(S::count_operations(num1, num2), expected);
}
}
}

0 comments on commit 2faa3fd

Please sign in to comment.