2429: Minimize-XOR
Medium
table of contents
This question is also a lot simpler than what it first appears.
Logically, it makes sense that you start to find x
by
making x = num1
and then continue to add/substract
bits. If we denote bits1
and bits2
as the
number of set bits in num1
and
num2
respectively, then we have 3 potential
outcomes:
Then, we just remove / add bits until the number of set bits
in x
is equal to the bits in
num1s
.
code
class Solution {
public:
int minimizeXor(int num1, int num2) {
int bits1 = __builtin_popcount(num1), bits2 = __builtin_popcount(num2);
int ans = num1;
int index = 0;
while(bits1 != bits2) {
if (bits1 < bits2 && (1 << index & ans) == 0) {
^= 1 << index;
ans ++bits1;
} else if (bits1 > bits2 && (1 << index & ans) > 0) {
^= 1 << index;
ans --bits1;
}
++index;
}
return ans;
}
};
complexity
any learnings:
__builtin_popcount(num)
returns the number of set bits innum