LeetCode 2429: Minimize XOR
Problem Description
Explanation
To solve this problem, we need to find a number x
that has the same number of set bits as num2
, and when XORed with num1
, gives the minimal result. We can achieve this by iteratively trying out different values of x
that have the same number of set bits as num2
and calculating the XOR value with num1
to find the minimum.
- Count the number of set bits in
num2
. - Iterate from
x = 0
tox = 2^32 - 1
(as we are dealing with 32-bit integers) and for eachx
:- Count the number of set bits in
x
. - If the count matches the count from step 1, calculate the XOR of
x
andnum1
. - Update the minimum XOR value and corresponding
x
if the calculated XOR is less than the current minimum.
- Count the number of set bits in
- Return the
x
that gives the minimum XOR value.
By iterating through all possible values of x
with the same number of set bits as num2
, we can find the solution to this problem.
Time complexity: O(1) as we iterate through all possible 32-bit integers Space complexity: O(1)
Solutions
class Solution {
public int minimizeXOR(int num1, int num2) {
int countSetBitsNum2 = Integer.bitCount(num2);
int min = Integer.MAX_VALUE;
int result = 0;
for (int x = 0; x <= Integer.MAX_VALUE; x++) {
if (Integer.bitCount(x) == countSetBitsNum2) {
int xor = x ^ num1;
if (xor < min) {
min = xor;
result = x;
}
}
}
return result;
}
}
Loading editor...