Problem Description
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.
Key Insights
- Compare the binary representations of
n
andk
. - Count the number of bits that differ between
n
andk
. - Ensure that
k
does not have any bits set to 1 at positions wheren
has bits set to 0. - The number of changes needed is equal to the count of differing bits that can be changed.
Space and Time Complexity
Time Complexity: O(1) - The operations involve bitwise operations and counting bits, which are constant time operations. Space Complexity: O(1) - Only a few variables are used for counting and comparison.
Solution
To solve this problem, we will use bit manipulation techniques. We will:
- Use the XOR operation to determine the differing bits between
n
andk
. - Count the number of set bits in the result of the XOR operation, which indicates how many bits need to be changed.
- Check for each bit in
k
to ensure that it does not require a change from a position wheren
has a 0.