Minimize XOR Problem
Description
LeetCode Problem 2429.
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 <= 10^9
Solution
Approach: Greedy + Bit Manipulation
Let cnt be the number of set bits in num2; x must have exactly cnt set bits. To make x XOR num1 small, first cover the highest set bits of num1: go from the top bit down and set the bit in x wherever num1 has a 1, until cnt runs out. If bits are still left, set the lowest positions where num1 has a 0, from the bottom up.
Complexity: The time complexity is O(log n) and the space complexity is O(1), where n is the largest of num1 and num2.
class Solution:
def minimizeXor(self, num1: int, num2: int) -> int:
cnt = bin(num2).count("1")
x = 0
for i in range(30, -1, -1):
if num1 >> i & 1 and cnt:
x |= 1 << i
cnt -= 1
for i in range(30):
if num1 >> i & 1 ^ 1 and cnt:
x |= 1 << i
cnt -= 1
return x