Problem Description
Given two positive integers num1 and num2, find a positive integer x such that:
- x has the same number of set bits (1’s) in its binary representation as num2.
- The value (x XOR num1) is minimized.
The problem guarantees that there is a unique integer x that satisfies these conditions.
Key Insights
- To minimize (x XOR num1), x should be as "similar" as possible to num1.
- Since x must have exactly k set bits (where k = the number of set bits in num2), the best strategy is to retain as many of num1's set bits as possible.
- If num1 contains more than k set bits, we remove some set bits from num1. To minimize the XOR value, it is best to remove bits with lower significance (i.e. the ones contributing less to the total value).
- If num1 contains fewer than k set bits, we add additional set bits to positions where num1 has a 0, again choosing the positions with the smallest weights first to keep the XOR difference minimal.
- This greedy approach, by working with bit positions starting from the least significant bit, ensures minimal contribution in the XOR result for any differences.
Space and Time Complexity
Time Complexity: O(32) ~ O(1) since we only iterate over a fixed number of bit positions. Space Complexity: O(1)
Solution
The solution involves the following steps:
- Count the number of set bits (ones) in num2 and num1.
- If num1 already has exactly the required number of set bits, return num1.
- If num1 has more set bits than required, identify positions where num1 has a 1. Then, from the least significant bit (lowest weight), unset bits until the number of 1’s equals the required count. Removing bits from lower positions minimizes the impact on the XOR value.
- If num1 has fewer set bits than required, identify positions where num1 has a 0. Then, set bits (starting from the least significant positions) until the total set bits equals the required count.
- Return the resulting integer.
Data structures used: Simple integer bit manipulations and iteration over bit positions (constant 32 iterations). The greedy approach is used to choose bits with lower significance first.