Skip to content

Commit c75bb51

Browse files
committed
Add C++ solution of problem #2429
1 parent 8c03598 commit c75bb51

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

2429/solution.cpp

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
class Solution {
2+
public:
3+
int minimizeXor(int num1, int num2) {
4+
int cnt = __builtin_popcount(num2);
5+
int ans = 0;
6+
7+
// first set the bits of ans in MSB order of num1
8+
for(int i = 31; (cnt > 0) && (i >= 0); i--) {
9+
if((num1 >> i) & 1) {
10+
ans |= (1 << i);
11+
cnt--;
12+
}
13+
}
14+
// set the remaining count of bits of ans in LSB order
15+
for(int i = 0; (cnt > 0) && (i < 31); i++) {
16+
if(!((ans >> i) & 1)) {
17+
ans |= (1 << i);
18+
cnt--;
19+
}
20+
}
21+
22+
return ans;
23+
}
24+
};

0 commit comments

Comments
 (0)