Number of Bit Changes to Make Two Integers Equal - Problem
You are given two positive integers n and k.
You can choose any bit in the binary representation of n that is equal to 1 and change it to 0.
Return the number of changes needed to make n equal to k. If it is impossible, return -1.
Input & Output
Example 1 — Basic Case
$
Input:
n = 13, k = 9
›
Output:
1
💡 Note:
n = 1101₂, k = 1001₂. Only bit 2 differs (1→0), so 1 change needed.
Example 2 — Impossible Case
$
Input:
n = 9, k = 13
›
Output:
-1
💡 Note:
n = 1001₂, k = 1101₂. Bit 2 needs to change from 0→1, which is impossible.
Example 3 — Already Equal
$
Input:
n = 5, k = 5
›
Output:
0
💡 Note:
n and k are already equal, no changes needed.
Constraints
- 1 ≤ n, k ≤ 106
- n and k are positive integers
Visualization
Tap to expand
Understanding the Visualization
1
Input
Two integers n=13 and k=9
2
Process
Find bits that need to change from 1 to 0
3
Output
Count of required bit changes
Key Takeaway
🎯 Key Insight: Use XOR to find different bits and validate that we only turn OFF bits (1→0)
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code