diff --git a/src/lib.rs b/src/lib.rs index 0902fe8..2486809 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -277,6 +277,7 @@ pub mod problem_0260_single_number_iii; pub mod problem_0268_missing_number; pub mod problem_0274_h_index; pub mod problem_0275_h_index_ii; +pub mod problem_0278_first_bad_version; pub mod problem_0283_move_zeroes; pub mod problem_0290_word_pattern; pub mod problem_0299_bulls_and_cows; diff --git a/src/problem_0278_first_bad_version/binary_search.rs b/src/problem_0278_first_bad_version/binary_search.rs new file mode 100644 index 0000000..751bec2 --- /dev/null +++ b/src/problem_0278_first_bad_version/binary_search.rs @@ -0,0 +1,44 @@ +use super::Solution as _; + +pub struct Solution { + bad: i32, +} + +impl Solution { + pub fn first_bad_version(&self, n: i32) -> i32 { + let mut left = 1; + let mut right = n; + while left < right { + let mid = (right - left) / 2 + left; + if self.isBadVersion(mid) { + right = mid; + } else { + left = mid + 1; + } + } + right + } +} + +impl super::Solution for Solution { + fn new(bad: i32) -> Self { + Self { bad } + } + + #[allow(non_snake_case)] // Expected. + fn isBadVersion(&self, version: i32) -> bool { + version >= self.bad + } + + fn first_bad_version(&self, n: i32) -> i32 { + self.first_bad_version(n) + } +} + +#[cfg(test)] +mod tests { + #[test] + fn test_solution() { + super::super::tests::run::(); + } +} diff --git a/src/problem_0278_first_bad_version/mod.rs b/src/problem_0278_first_bad_version/mod.rs new file mode 100644 index 0000000..9602b2c --- /dev/null +++ b/src/problem_0278_first_bad_version/mod.rs @@ -0,0 +1,23 @@ +pub mod binary_search; + +pub trait Solution { + fn new(bad: i32) -> Self; + + #[allow(non_snake_case)] // Expected. + fn isBadVersion(&self, version: i32) -> bool; + + fn first_bad_version(&self, n: i32) -> i32; +} + +#[cfg(test)] +mod tests { + use super::Solution; + + pub fn run() { + let test_cases = [((5, 4), 4), ((1, 1), 1)]; + + for ((n, bad), expected) in test_cases { + assert_eq!(S::new(bad).first_bad_version(n), expected); + } + } +}