We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Number of Bit Changes to Make Two Integers Equal

Difficulty: Easy


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 and k.
  • Count the number of bits that differ between n and k.
  • Ensure that k does not have any bits set to 1 at positions where n 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:

  1. Use the XOR operation to determine the differing bits between n and k.
  2. Count the number of set bits in the result of the XOR operation, which indicates how many bits need to be changed.
  3. Check for each bit in k to ensure that it does not require a change from a position where n has a 0.

Code Solutions

def numberOfBitChanges(n: int, k: int) -> int:
    if k > n:
        return -1

    # Count the number of bits that differ
    diff = n ^ k
    changes_needed = 0
    
    # Count the number of 1s in the diff
    while diff > 0:
        if diff & 1:
            changes_needed += 1
        diff >>= 1
    
    # Check if k has bits set that n does not
    for i in range(20):  # Since n and k are <= 10^6, we check up to 20 bits
        if (k & (1 << i)) and not (n & (1 << i)):
            return -1
            
    return changes_needed
← Back to All Questions