LeetCode 2429. Minimize XOR Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
2429. Minimize XOR

Description

Given two positive integers num1 and num2, find the positive integer x such that:

  • x has the same number of set bits as num2, and
  • The value x XOR num1 is 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

According to the problem description, we first calculate the number of set bits in num2, denoted as cnt. Then, we iterate from the highest to the lowest bit of num1; if the current bit is 1, we set the corresponding bit in x to 1 and decrement cnt, until cnt becomes 0. If cnt is still not 0, we iterate from the lowest bit upwards, setting positions where num1 has 0 to 1 in x, and decrement cnt until it reaches 0.

The time complexity is O(log n), where n is the maximum value of num1 and num2. The space complexity is O(1).

PythonJavaC++GoTypeScriptRustC#
class Solution: def minimizeXor(self, num1: int, num2: int) -> int: cnt = num2.bit_count() 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(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !