If you're preparing for coding interviews or competitive programming, "Minimize XOR" is a fascinating problem to test your understanding of bit manipulation.
Problem
You are given two positive integers, num1 and num2. Your task is to find a positive integer x such that:
x has the same number of set bits (1s in its binary representation) as num2.
The value of x XOR num1 is minimized.
The result must be uniquely determined, and the test cases are guaranteed to meet this condition.
What is XOR?
Before we jump into the solution, let’s quickly revisit what XOR (Exclusive OR) is. XOR is a bitwise operation:
If two bits are the same (both 0 or both 1), the result is 0.
If two bits are different (one is 0, the other is 1), the result is 1.
To achieve this, we need to be as "similar" as possible to , especially in the higher significant bits.
Understand the Problem with Examples
Let’s go through a couple of examples to understand the requirements better:
Example 1:
Input: num1 = 3, num2 = 5
Number of set bits in : 2
We need to construct an integer that:
Has exactly 2 set bits.
Example 2:
Input: num1 = 1, num2 = 12
Number of set bits : 2
Again, we need with exactly 2 set bits, minimizing .
Approach to Solve the Problem
The problem boils down to constructing such that:
It has the same number of set bits.
The difference between and (in terms of bit values) is minimal.
To achieve this, we follow these steps:
Step 1: Count Set Bits in num2
Count the number of set bits (1s) in nums2. Let’s call this count . This tells us how many bits in need to be set to num1.
Step 2: Reuse Set Bits from num1
To minimize , we prioritize reusing the set bits (1s) from MSB. Starting from the most significant bit of num1, we check if a bit is set (1). If it is, we include it in and reduce by 1.
Step 3: Fill Remaining Bits
If after processing all bits of num1, we set the remaining bits in x, starting from the least significant bit (to keep as small as possible).
Step 4: Return the Result
Finally, return as the result.
Algorithm
Count the number of set bits in num2.
Initialize x = 0 .
Iterate through the bits of from the most significant bit to the least significant bit:
If the current bit of is set (1), set the corresponding bit in and decrement .
Stop when reaches 0.
If , iterate through all bits starting from the least significant bit:
Set the bit in x, if it is not already set.
Decrement after each change.
Return x.
Complexity Analysis
Time Complexity: O(1)
We iterate through a fixed number of bits (32 for integers).
Space Complexity: O(1)
We use a constant amount of extra space.