-
Notifications
You must be signed in to change notification settings - Fork 21
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add problem 2169: Count Operations to Obtain Zero
- Loading branch information
Showing
3 changed files
with
60 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
41 changes: 41 additions & 0 deletions
41
src/problem_2169_count_operations_to_obtain_zero/mathematical.rs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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>(); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} | ||
} | ||
} |