From 76e2459dd5ba51b940211d240eed2f9d0405c5ea Mon Sep 17 00:00:00 2001 From: Spxg Date: Fri, 17 May 2024 13:32:23 +0800 Subject: [PATCH] Add problem 0201: Bitwise AND of Numbers Range --- src/lib.rs | 1 + .../bit_manipulation.rs | 31 +++++++++++++++++++ .../mod.rs | 18 +++++++++++ 3 files changed, 50 insertions(+) create mode 100644 src/problem_0201_bitwise_and_of_numbers_range/bit_manipulation.rs create mode 100644 src/problem_0201_bitwise_and_of_numbers_range/mod.rs diff --git a/src/lib.rs b/src/lib.rs index 98de5c1..586e98e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -253,6 +253,7 @@ pub mod problem_0190_reverse_bits; pub mod problem_0191_number_of_1_bits; pub mod problem_0198_house_robber; pub mod problem_0199_binary_tree_right_side_view; +pub mod problem_0201_bitwise_and_of_numbers_range; pub mod problem_0202_happy_number; pub mod problem_0203_remove_linked_list_elements; pub mod problem_0205_isomorphic_strings; diff --git a/src/problem_0201_bitwise_and_of_numbers_range/bit_manipulation.rs b/src/problem_0201_bitwise_and_of_numbers_range/bit_manipulation.rs new file mode 100644 index 0000000..6599887 --- /dev/null +++ b/src/problem_0201_bitwise_and_of_numbers_range/bit_manipulation.rs @@ -0,0 +1,31 @@ +pub struct Solution; + +impl Solution { + pub fn range_bitwise_and(left: i32, right: i32) -> i32 { + let mut left = left; + let mut right = right; + let mut shift = 0; + + while left != right { + left >>= 1; + right >>= 1; + shift += 1; + } + + left << shift + } +} + +impl super::Solution for Solution { + fn range_bitwise_and(m: i32, n: i32) -> i32 { + Self::range_bitwise_and(m, n) + } +} + +#[cfg(test)] +mod tests { + #[test] + fn test_solution() { + super::super::tests::run::(); + } +} diff --git a/src/problem_0201_bitwise_and_of_numbers_range/mod.rs b/src/problem_0201_bitwise_and_of_numbers_range/mod.rs new file mode 100644 index 0000000..9ed8edf --- /dev/null +++ b/src/problem_0201_bitwise_and_of_numbers_range/mod.rs @@ -0,0 +1,18 @@ +pub mod bit_manipulation; + +pub trait Solution { + fn range_bitwise_and(m: i32, n: i32) -> i32; +} + +#[cfg(test)] +mod tests { + use super::Solution; + + pub fn run() { + let test_cases = [((5, 7), 4), ((0, 1), 0), ((2, 2), 2)]; + + for ((m, n), expected) in test_cases { + assert_eq!(S::range_bitwise_and(m, n), expected); + } + } +}