Number of Bit Changes to Make Two Integers Equal - Problem
Given two positive integers n and k, you need to determine the minimum number of bit changes required to transform n into k.
The twist? You can only change bits from 1 to 0 in the binary representation of n. You cannot change bits from 0 to 1.
Goal: Return the number of changes needed to make n equal to k. If it's impossible to transform n into k with the allowed operations, return -1.
Example: If n = 13 (binary: 1101) and k = 4 (binary: 0100), we need to change the 1st and 4th bits from 1 to 0, requiring 2 changes.
Input & Output
example_1.py โ Basic Transformation
$
Input:
n = 13, k = 4
โบ
Output:
2
๐ก Note:
n = 13 is 1101 in binary, k = 4 is 0100 in binary. We need to change the 1st bit (1โ0) and 4th bit (1โ0), requiring 2 changes total.
example_2.py โ Impossible Case
$
Input:
n = 10, k = 7
โบ
Output:
-1
๐ก Note:
n = 10 is 1010 in binary, k = 7 is 0111 in binary. k has 1s in positions where n has 0s (positions 1 and 3), making transformation impossible since we can only change 1โ0.
example_3.py โ Already Equal
$
Input:
n = 5, k = 5
โบ
Output:
0
๐ก Note:
Both numbers are already equal (5 = 0101 in binary), so no changes are needed.
Constraints
- 1 โค n, k โค 106
- Both n and k are positive integers
- Only 1โ0 transformations are allowed
Visualization
Tap to expand
Understanding the Visualization
1
Check Possibility
Verify that target pattern doesn't require turning any switch ON
2
Find Differences
Identify which switches need to be turned OFF
3
Count Changes
Count how many switches need to be flipped
Key Takeaway
๐ฏ Key Insight: Use bitwise AND to check feasibility, then XOR to find differences efficiently
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code