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
Light Switch TransformationCurrent State (n=13)ONBit 3ONBit 2OFFBit 1ONBit 0Target State (k=4)OFFBit 3ONBit 2OFFBit 1OFFBit 02 switches need to be turned OFF
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
Asked in
Google 42 Amazon 35 Microsoft 28 Meta 22
38.2K Views
Medium Frequency
~15 min Avg. Time
1.3K 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