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
Bit Changes: Transform n=13 to k=9n = 13 (binary):1101bit 3bit 2bit 1bit 0Change bit 2: 1 → 0k = 9 (binary):1001Result: 1 bit change needed
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)
Asked in
Microsoft 25 Google 20 Amazon 15
21.3K Views
Medium Frequency
~10 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen