diff --git a/2429. Minimize XOR b/2429. Minimize XOR new file mode 100644 index 0000000..c768631 --- /dev/null +++ b/2429. Minimize XOR @@ -0,0 +1,28 @@ +class Solution { + public int minimizeXor(int num1, int num2) { + if(num1 == num2) return num1; + + int bit = Integer.bitCount(num2); + + int ans = 0; + + for(int i=31;i>=0;i--) { + int currBit = (num1 >> i) & 1; + if(currBit == 1 && bit > 0) { + ans |= (1 << i); + bit--; + } + } + + // if bits to set are remaining, set the `LSB` + for(int i=0;i<32;i++) { + if(bit == 0) break; + int currBit = (ans >> i) & 1; + if(currBit != 1) { + ans |= (1 << i); + bit--; + } + } + return ans; + } +}