#2429
Minimize XOR
specialist · 680 · lc medium +30 · verified · 62.4% accepted · 1,091 likes · top 64%
Description
Given two positive integers num1 and num2, find a positive integer x such that:
- The popcount (number of set bits) of x equals the popcount of num2.
- The value x XOR num1 is minimized.
Return x. If multiple answers minimize the XOR, return the one with fewer set bits.
Example 1:
Input: num1 = 3, num2 = 5
Output: 3
Explanation:
The binary representations of num1 and num2 are 0011 and 0101, respectively.
The integer 3 has the same number of set bits as num2, and the value 3 XOR 3 = 0 is minimal.
Example 2:
Input: num1 = 1, num2 = 12
Output: 3
Explanation:
The binary representations of num1 and num2 are 0001 and 1100, respectively.
The integer 3 has the same number of set bits as num2, and the value 3 XOR 1 = 2 is minimal.
Code
1
2
3