-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathsolution.cpp
41 lines (39 loc) · 1 KB
/
solution.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
class Solution
{
public:
int minimizeXor(int num1, int num2)
{
int count2 = __builtin_popcount(num2); // Number of 1s in num2
int count1 = __builtin_popcount(num1); // Number of 1s in num1
if (count1 == count2)
{
return num1; // Already satisfies the condition
}
int result = num1;
if (count1 > count2)
{
// Remove extra 1s
for (int i = 0; i < 32 && count1 > count2; ++i)
{
if (result & (1 << i))
{
result &= ~(1 << i); // Clear bit
count1--;
}
}
}
else
{
// Add additional 1s
for (int i = 0; i < 32 && count1 < count2; ++i)
{
if (!(result & (1 << i)))
{
result |= (1 << i); // Set bit
count1++;
}
}
}
return result;
}
};