2429: Minimize-XOR
Medium

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) {
                ans ^= 1 << index;
                ++bits1;
            } else if (bits1 > bits2 && (1 << index & ans) > 0) {
                ans ^= 1 << index;
                --bits1;
            }
            ++index;
        }
        return ans;
    }
};

Complexity:

any learnings: