2429. Minimize XOR
Description
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.
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.
Constraints:
1 <= num1, num2 <= 109
Solutions
Solution 1: Greedy + Bit Manipulation
Thinking
\(x\) must have the same popcount as \(num2\) and minimize \(x\oplus num1\), so \(x\) should reuse \(num1\)'s high \(1\)-bits. At most \(31\) bits, greedy by position works.
First take \(num1\)'s \(1\)-bits from high to low; if slots remain, fill \(num1\)'s \(0\)-bits from low to high so the XOR does not grow in high bits.
According to the problem description, we first calculate the number of set bits in \(\textit{num2}\), denoted as \(\textit{cnt}\). Then, we iterate from the highest to the lowest bit of \(\textit{num1}\); if the current bit is \(1\), we set the corresponding bit in \(x\) to \(1\) and decrement \(\textit{cnt}\), until \(\textit{cnt}\) becomes \(0\). If \(\textit{cnt}\) is still not \(0\), we iterate from the lowest bit upwards, setting positions where \(\textit{num1}\) has \(0\) to \(1\) in \(x\), and decrement \(\textit{cnt}\) until it reaches \(0\).
The time complexity is \(O(\log n)\), where \(n\) is the maximum value of \(\textit{num1}\) and \(\textit{num2}\). The space complexity is \(O(1)\).
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | |