Minimize XOR

Medium Topics Company Tags

Find the positive integer x with the same number of set bits as num2 that minimizes x XOR num1. Return x, rather than the XOR value. A set bit is a 1 in the binary representation, and the minimizing integer is unique.

Example 1:

Input: num1 = 10
num2 = 7

Output: 11

Explanation: The number 7 has three set bits. Choosing x = 11, binary 1011, keeps both set bits of 10 and adds the lowest unset bit. The resulting XOR is 1, the smallest possible.

Example 2:

Input: num1 = 15
num2 = 2

Output: 8

Explanation: The number 2 has one set bit. Among numbers with one set bit, x = 8 gives the smallest XOR with 15: 8 XOR 15 = 7.

Example 3:

Input: num1 = 8
num2 = 3

Output: 9

Explanation: The number 3 has two set bits. Choosing x = 9, binary 1001, preserves the high bit of 8 and adds the lowest bit, yielding XOR 1.

Constraints:

  • 1 <= num1, num2 <= 1000000000


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.