[LeetCode] Minimize XOR

2429. Minimize XOR

Given two positive integers num1 and num2, find the integer x such that:

  • x has the same number of set bits as num2, and
  • The value x XOR num1 is minimal.

Note that XOR is the bitwise XOR operation.

Return the integer x. The test cases are generated such that x is uniquely determined.

The number of set bits of an integer is the number of 1’s in its binary representation.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
public:
int minimizeXor(int num1, int num2) {
int bi2 = __builtin_popcount(num2);
int bi1 = __builtin_popcount(num1);
if(bi2 == bi1) return num1;
if(bi2 > bi1) {
int res = num1, req = bi2 - bi1;
for(int i = 0; i < 32 and req; i++) {
if(num1 & (1<<i)) continue;
res |= (1<<i);
req--;
}
return res;
}
int res = 0;
for(int i = 32; i >= 0 and bi2; i--) {
if(num1 & (1ll<<i)) {
res ^= (1ll<<i);
bi2--;
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/10/02/PS/LeetCode/minimize-xor/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.