Skip to content

Commit

Permalink
Add problem 0201: Bitwise AND of Numbers Range
Browse files Browse the repository at this point in the history
  • Loading branch information
Spxg committed May 17, 2024
1 parent f68b2e9 commit 76e2459
Show file tree
Hide file tree
Showing 3 changed files with 50 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 @@ -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;
Expand Down
31 changes: 31 additions & 0 deletions src/problem_0201_bitwise_and_of_numbers_range/bit_manipulation.rs
Original file line number Diff line number Diff line change
@@ -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::<super::Solution>();
}
}
18 changes: 18 additions & 0 deletions src/problem_0201_bitwise_and_of_numbers_range/mod.rs
Original file line number Diff line number Diff line change
@@ -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<S: Solution>() {
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);
}
}
}

0 comments on commit 76e2459

Please sign in to comment.