[LeetCode] Number of Bit Changes to Make Two Integers Equal

3226. Number of Bit Changes to Make Two Integers Equal

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
int minChanges(int n, int k) {
int res = 0;
while(n or k) {
bool a = n & 1, b = k & 1;
n /= 2, k /= 2;
if(a == b) continue;
if(b == 1) return -1;
res++;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/07/21/PS/LeetCode/number-of-bit-changes-to-make-two-integers-equal/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.