diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 21f6de6..eb01e88 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -290,3 +290,5 @@ mod p3216_lexicographically_smallest_string_after_a_swap; mod p3165_maximum_sum_of_subsequence_with_non_adjacent_elements; mod p3259_maximum_energy_boost_from_two_drinks; + +mod p3226_number_of_bit_changes_to_make_two_integers_equal; diff --git a/src/problem/p3226_number_of_bit_changes_to_make_two_integers_equal.rs b/src/problem/p3226_number_of_bit_changes_to_make_two_integers_equal.rs new file mode 100644 index 0000000..9077c1c --- /dev/null +++ b/src/problem/p3226_number_of_bit_changes_to_make_two_integers_equal.rs @@ -0,0 +1,54 @@ +/** + * [3226] Number of Bit Changes to Make Two Integers Equal + */ +pub struct Solution {} + +// submission codes start here + +impl Solution { + pub fn min_changes(n: i32, k: i32) -> i32 { + if n == k { + return 0; + } + + let (mut n, mut k) = (n, k); + let mut result = 0; + + while n != 0 { + if n % 2 == 0 { + if k % 2 != 0 { + result = -1; + break; + } + } else { + if k % 2 != 1 { + result += 1; + } + } + + k = k / 2; + n = n / 2; + } + + if k != 0 { + -1 + } else { + result + } + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_3226() { + assert_eq!(2, Solution::min_changes(13, 4)); + assert_eq!(0, Solution::min_changes(21, 21)); + assert_eq!(-1, Solution::min_changes(14, 13)); + assert_eq!(-1, Solution::min_changes(11, 56)); + } +}