My approach was to construct (x)
by considering the bits of num1
and num2
. First, I counted the number of set bits in num2
using Python's bin(num2).count('1')
.
To minimize the XOR value, I prioritized aligning (x)
with the bits of num1
where possible. Starting from the most significant bit, I iterated through all the bits of num1
. Whenever I met a set bit (1) in num1
and still needed more set bits in (x)
, I copied that bit into (x)
. This helped (x)
resemble num1
, minimizing their XOR value.
If the required number of set bits was not achieved after aligning with num1
, I switched to filling (x)
with additional set bits from the least significant bit upward.
Finally, I returned (x)
.
class Solution:
def minimizeXor(self, num1: int, num2: int) -> int:
set_bits_num2 = bin(num2).count('1')
result = 0
set_bits_added = 0
for i in range(31, -1, -1):
if (num1 & (1 << i)) != 0 and set_bits_added < set_bits_num2:
result |= (1 << i)
set_bits_added += 1
for i in range(32):
if set_bits_added >= set_bits_num2:
break
if (result & (1 << i)) == 0:
result |= (1 << i)
set_bits_added += 1
return result
- Time: O(log M), where
(M)
is the value ofnum2
. - Space: O(log M), for binary representation during set bit counting.
