All problems
1124MediumGreedyBit Manipulation

Matching the Notch Count as Closely as You Can

Tracked in this browser only
Write code

Trains the technique from

LeetCode 2429Minimize XOR

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

Two whole numbers num1 and num2 are given. Build a whole number x carrying exactly as many 1 bits as num2 does, chosen so that the bitwise exclusive-or of x and num1 comes out as small as possible.

Return x. Exactly one number meets both demands.

Examples

Example 1

Input
num1 = 8, num2 = 3
Output
9

Two bits are allowed. Keeping the bit num1 already carries costs nothing, and the cheapest home for the second is the lowest free place.

Example 2

Input
num1 = 15, num2 = 1
Output
8

Only one bit is allowed, so three of num1's four bits have to go. Dropping the highest would cost more than dropping all the others, so that is the one kept.

Example 3

Input
num1 = 1, num2 = 15
Output
15

Four bits are needed and num1 supplies one of them. The other three take the lowest free places, which is the smallest number with four bits.

Constraints

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

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def minimize_xor(num1: int, num2: int) -> int:
Java
public int minimizeXor(int num1, int num2)
September 7
Apply