LeetCode 2429, Medium. Topics: Greedy, Bit Manipulation. View on LeetCode.
Generate this problem as a practice environment: tested reference solution, 20 parametrized pytest cases, and a playground notebook:
Problem
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.
Examples
Constraints
Solution
Reference implementation from solution.py on GitHub, full suite in test_solution.py:
Complexity
NeetCode All. Last modified on September 7, 2026