[translate by ChatGPT]
At first I didn’t fully understand the problem, but later I figured it out. We need to count how many 1’s are in the binary representation of num2, then find a number ans that has the same number of 1’s and minimizes the XOR value between num1 and ans.
My initial idea was: after counting the number of set bits, match all the 1-bits in num1 first, and then fill the remaining bits starting from the smallest positions.
Later I realized there is a case where we cannot finish matching all the 1-bits of num1. In that situation, we should match the higher bits first, and only then fill the smaller bits. In the future, I should question whether “matching all bits of num1 first” is always a valid assumption and consider the possibility that it may not fully cover the cases.
Also, when selecting bits, we should decrement setBit during the selection process. I originally computed it outside the loop, which caused some bugs. In the future, I should try throwing in my own corner cases to test correctness.
Code
class Solution {
public:
int minimizeXor(int num1, int num2) {
short setBit = 0;
while(num2 > 0) {
if ((num2 & 1) == 1) {
++setBit;
}
num2 /= 2;
}
short cnt = 0;
unordered_set<short> ansAry;
while(num1 > 0) {
if ((num1 & 1) == 1) {
ansAry.insert(cnt);
}
num1 /= 2;
++cnt;
}
int ans = 0;
for(int i = 31 ; i >= 0 ; --i) {
if (setBit == 0) {
break;
}
if (ansAry.find(i) != ansAry.end()) {
ans += (1 << i);
--setBit;
}
}
for(int i = 0 ; i < 31 ; ++i) {
if (setBit == 0) {
break;
}
if (ansAry.find(i) == ansAry.end()) {
ans += (1 << i);
--setBit;
}
}
return ans;
}
};