Number of Bit Changes to Make Two Integers Equal
EasyPrompt
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.
Example 1:
Input: n = 13, k = 4
Output: 2
Explanation:
Initially, the binary representations of n and k are n = (1101)2 and k = (0100)2.
We can change the first and fourth bits of n. The resulting integer is n = (0100)2 = k.
Example 2:
Input: n = 21, k = 21
Output: 0
Explanation:
n and k are already equal, so no changes are needed.
Example 3:
Input: n = 14, k = 13
Output: -1
Explanation:
It is not possible to make n equal to k.
Constraints:
1 <= n, k <= 106
Approaches
3 approaches with complexity analysis and trade-offs.
This approach involves converting both integers n and k into their binary string representations. After ensuring both strings have the same length by padding the shorter one with leading zeros, we can iterate through them character by character to check for the conditions of the problem.
Algorithm
- Convert
nandkto binary strings,nStrandkStr. - Determine the maximum length between
nStrandkStr. - Pad the shorter string with leading zeros to match the maximum length.
- Initialize a
changescounter to 0. - Iterate through the strings from
i = 0tolength - 1. - At each position
i, comparenStr.charAt(i)andkStr.charAt(i). - If
nStr.charAt(i) == '0'andkStr.charAt(i) == '1', return -1. - If
nStr.charAt(i) == '1'andkStr.charAt(i) == '0', incrementchanges. - After the loop, return
changes.
Walkthrough
The core idea is to work with the numbers as text.
- First, we obtain the binary strings for
nandkusingInteger.toBinaryString(). - The binary strings might have different lengths. To compare them bit by bit, we need to align them. We find the maximum length and pad the shorter string with leading '0's until it matches the maximum length.
- We then iterate through the aligned strings from left to right (most significant to least significant bit).
- For each position
i, we compare the charactersn_str.charAt(i)andk_str.charAt(i).- If
nhas a '0' wherekhas a '1', the transformation is impossible, as we cannot change a '0' to a '1'. We return -1 immediately. - If
nhas a '1' wherekhas a '0', this is a required change. We increment a counter. - If the bits are the same, no action is needed.
- If
- If the loop completes without finding an impossible case, the final value of the counter is our answer.
class Solution { public int minChanges(int n, int k) { String nStr = Integer.toBinaryString(n); String kStr = Integer.toBinaryString(k); int nLen = nStr.length(); int kLen = kStr.length(); int maxLen = Math.max(nLen, kLen); // Pad with leading zeros to make lengths equal while (nStr.length() < maxLen) { nStr = "0" + nStr; } while (kStr.length() < maxLen) { kStr = "0" + kStr; } int changes = 0; for (int i = 0; i < maxLen; i++) { char nBit = nStr.charAt(i); char kBit = kStr.charAt(i); if (nBit == '0' && kBit == '1') { return -1; // Impossible to change 0 to 1 } if (nBit == '1' && kBit == '0') { changes++; // Required change from 1 to 0 } } return changes; }}Complexity
Time
O(log(max(n, k))). The length of the binary representation of a number `x` is proportional to `log(x)`. String operations like conversion and padding take time proportional to this length.
Space
O(log(max(n, k))) to store the binary string representations of `n` and `k`.
Trade-offs
Pros
Conceptually straightforward, especially for those more comfortable with string manipulation than bitwise operations.
Cons
Inefficient due to the overhead of string creation, concatenation (for padding), and character-by-character access.
The implementation is more verbose compared to bitwise solutions.
Solutions
Solution
class Solution {public int minChanges(int n, int k) { return (n & k) != k ? -1 : Integer.bitCount(n ^ k); }}Video walkthrough
Newsletter
One sharp idea, every week
System design and interview prep — short enough to finish.
No spam. Unsubscribe anytime.
Practice
Same difficulty — related problems to reinforce the pattern.