-
Notifications
You must be signed in to change notification settings - Fork 3
/
2429.cpp
48 lines (47 loc) · 1.16 KB
/
2429.cpp
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
class Solution {
public:
int minimizeXor(int num1, int num2) {
int n = __builtin_popcount(num2);
int m = __builtin_popcount(num1);
int res = 0;
int index = 0;
if (m > n) {
vector<bool> v;
while (num1 > 0) {
if (num1 & 1) {
v.push_back(true);
}
else v.push_back(false);
index++;
num1 >>= 1;
}
int k = v.size() - 1;
while (n > 0) {
if (v[k] == true) {
res += (1 << k);
n--;
}
k--;
}
return res;
}
if (m == n) return num1;
while (num1 && n > 0) {
if (num1 & 1) {
res += (1 << index);
n--;
}
index++;
num1 >>= 1;
}
index = 0;
while (n > 0) {
if ((((res & (1 << index)) >> index) & 1) == 0) {
res += (1 << index);
n--;
}
index++;
}
return res;
}
};