Minimize XOR - Problem
Given two positive integers num1 and num2, find the positive integer x such that:
xhas the same number of set bits asnum2, and- The value
x XOR num1is minimal.
Note that XOR is the bitwise XOR operation.
Return the integer x. The test cases are generated such that x is uniquely determined.
The number of set bits of an integer is the number of 1's in its binary representation.
Input & Output
Example 1 — Perfect Match
$
Input:
num1 = 3, num2 = 5
›
Output:
3
💡 Note:
num1 = 3 (binary: 011) has 2 set bits. num2 = 5 (binary: 101) has 2 set bits. Since 3 already has the required number of bits, x = 3 gives XOR = 0, which is minimal.
Example 2 — Need More Bits
$
Input:
num1 = 1, num2 = 12
›
Output:
3
💡 Note:
num1 = 1 (binary: 001) has 1 set bit. num2 = 12 (binary: 1100) has 2 set bits. We need x with 2 set bits. Starting from 1, we add the lowest bit to get 3 (binary: 011). XOR: 3 ⊕ 1 = 2.
Example 3 — Need Fewer Bits
$
Input:
num1 = 25, num2 = 6
›
Output:
17
💡 Note:
num1 = 25 (binary: 11001) has 3 set bits. num2 = 6 (binary: 110) has 2 set bits. We need x with 2 set bits. Remove the highest bit from 25 to get 17 (binary: 10001) with 2 set bits.
Constraints
- 1 ≤ num1, num2 ≤ 109
- num1 and num2 are positive integers
Visualization
Tap to expand
Understanding the Visualization
1
Input Analysis
Analyze bit patterns of num1 and num2
2
Bit Optimization
Construct x to minimize XOR
3
Result
x with required bits and minimal XOR
Key Takeaway
🎯 Key Insight: Start with num1 and greedily adjust bit count to minimize XOR while maintaining the required number of set bits
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code