Minimize XOR
Preview mode. Log in to edit, run, submit, and save progress.
Medium
Minimize XOR
Given two positive integers num1 and num2, return an integer x such that: x has the same number of set bits as num2. x XOR num1 is as small as possible. The answer is guaranteed to be unique.
Examples
Example 1
Input:
num1 = 3, num2 = 5
Output:
3
Explanation: num2 = 5 has two set bits. The number 3 also has two set bits, and 3 XOR 3 = 0.
Approach hint
Start with the simplest clear approach, explain the trade-off, then move toward the cleaner answer.
Common mistake
Skipping assumptions, edge cases, or trade-offs can make an otherwise good answer feel incomplete.
solution.cpp