-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathsolution.java
30 lines (28 loc) · 937 Bytes
/
solution.java
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
class Solution {
public int minimizeXor(int num1, int num2) {
int count2 = Integer.bitCount(num2); // Number of 1s in num2
int count1 = Integer.bitCount(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)) != 0) {
result &= ~(1 << i); // Clear bit
count1--;
}
}
} else {
// Add additional 1s
for (int i = 0; i < 32 && count1 < count2; i++) {
if ((result & (1 << i)) == 0) {
result |= (1 << i); // Set bit
count1++;
}
}
}
return result;
}
}