Minimize XOR

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
Inputnum1 = 3, num2 = 5
Output3
The binary representations of num1 and num2 are 0011 and 0101, respectively; 3 has the same number of set bits as num2, and 3 XOR 3 = 0 is minimal.
Example 2
Inputnum1 = 1, num2 = 12
Output3
The binary representations of num1 and num2 are 0001 and 1100, respectively; 3 has the same number of set bits as num2, and 3 XOR 1 = 2 is minimal.

Constraints

  • 1 <= num1, num2 <= 10^9

Asked at 6 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate