2429. Minimize XOR

1 min read

class Solution:
def minimizeXor(self, num1: int, num2: int) -> int:
bits1 = bin(num1).count('1')
bits2 = bin(num2).count('1')
if bits2 < bits1:
check = "1"
replaceWith = "0"
else:
check = "0"
replaceWith = "1"
diff = abs(bits1 - bits2)
x = list(bin(num1))[2:]
x.reverse()
for i, e in enumerate(x):
if not diff:
break
if e == check:
x[i] = replaceWith
diff -= 1
if not diff:
break
x.reverse()
return int("0b" + (diff * "1") + "".join(x), 2)
0
Subscribe to my newsletter
Read articles from Tapan Rachchh directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
