Skip to content

Commit

Permalink
Add problem 2220: Minimum Bit Flips to Convert Number
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Mar 19, 2024
1 parent d1a7681 commit 5eef643
Show file tree
Hide file tree
Showing 3 changed files with 44 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 @@ -1482,6 +1482,7 @@ pub mod problem_2190_most_frequent_number_following_key_in_an_array;
pub mod problem_2194_cells_in_a_range_on_an_excel_sheet;
pub mod problem_2206_divide_array_into_equal_pairs;
pub mod problem_2215_find_the_difference_of_two_arrays;
pub mod problem_2220_minimum_bit_flips_to_convert_number;

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

pub trait Solution {
fn min_bit_flips(start: i32, goal: i32) -> i32;
}

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

pub fn run<S: Solution>() {
let test_cases = [((10, 7), 3), ((3, 4), 3)];

for ((start, goal), expected) in test_cases {
assert_eq!(S::min_bit_flips(start, goal), expected);
}
}
}
25 changes: 25 additions & 0 deletions src/problem_2220_minimum_bit_flips_to_convert_number/xor.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
pub struct Solution;

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

impl Solution {
pub fn min_bit_flips(start: i32, goal: i32) -> i32 {
(start ^ goal).count_ones() as _
}
}

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

impl super::Solution for Solution {
fn min_bit_flips(start: i32, goal: i32) -> i32 {
Self::min_bit_flips(start, goal)
}
}

#[cfg(test)]
mod tests {
#[test]
fn test_solution() {
super::super::tests::run::<super::Solution>();
}
}

0 comments on commit 5eef643

Please sign in to comment.