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 to Make Two Integers Equal INPUT n = 13 (binary) 1 1 0 1 bit3 bit2 bit1 bit0 k = 9 (binary) 1 0 0 1 bit3 bit2 bit1 bit0 Input Values n = 13, k = 9 1101 vs 1001 ALGORITHM STEPS 1 Check Feasibility If k has 1 where n has 0 --> return -1 2 XOR Operation diff = n XOR k 13 XOR 9 = 4 (0100) 3 Verify diff AND k = 0 4 AND 9 = 0 (OK) Can only flip 1-->0 4 Count Set Bits popcount(diff) popcount(4) = 1 Bit Comparison n: 1 1 0 1 k: 1 0 0 1 XOR: 0 1 0 0 (change bit2) FINAL RESULT Transformation Before (n=13) 1 1 0 1 After (k=9) 1 0 0 1 OUTPUT 1 bit change needed Key Insight: We can only change 1s to 0s in n. So if k has a 1 where n has a 0, it's impossible (return -1). XOR finds differing bits. If (n XOR k) AND k equals 0, we can transform n to k. The answer is popcount(n XOR k) - counting bits that need to flip from 1 to 0. TutorialsPoint - Number of Bit Changes to Make Two Integers Equal | Optimal Solution
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