#3226
Easy Algorithms Number of bit changes to make two integers equal
Bit Manipulation
63.4% acceptance
Feb 25, 2026
103
7
You are given two positive integers n and k.
You can choose any bit in the binary representation of n that is equal to 1 and change it to 0.
Return the number of changes needed to make n equal to k. If it is impossible, return -1.
Solution
Rust
Time O(1)
Space O(1)
impl Solution {
pub fn min_changes(n: i32, k: i32) -> i32 {
// k must be a submask of n (all bits of k must be in n)
if (k & !n) != 0 {
return -1;
}
// Count bits that are 1 in n but 0 in k
(n & !k).count_ones() as i32
}
}