WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Coding Interview Essentials · Bit Manipulation Problems · question 89 of 120

How would you determine the number of bits required to convert one given integer into another?

📕 Buy this interview preparation book: 120 Coding Interview Essentials questions & answers — PDF + EPUB for $5

To find the number of bits required to convert one integer into another, you can use the XOR bitwise operator. The XOR operator returns a bit where the corresponding bits of two operands are different. This means, if the corresponding bit values of two integers are different on the XOR operation, we would need to change that bit in the conversion.

Here’s your algorithm:

1. Compute the XOR of two numbers.

2. Count the number of set bits in the result from step 1. This will be the number of bits we need to change.

#### Code Example in Python

You can use this Python code as an example to compute the number of bits required to convert one integer into another.

def countBitsToConvert(a: int, b: int) -> int:
    # Step 1: Compute the XOR of two numbers
    n = a ^ b
    
    # Step 2: Count the number of set bits in the result
    count = 0
    while n:
        count += n & 1
        n >>= 1
    return count

# Test the function
a = 14 # represented as 01110 in binary
b = 31 # represented as 11111 in binary
print(countBitsToConvert(a, b))  # output: 1

In this example, the binary representation of numbers 14 and 31 is 01110 and 11111 respectively. Their XOR operation gives 10001. There is only one bit set (the bit in position 4 counting from zero from right to left), hence the number of bits required to convert 14 to 31 is 1.

The time complexity of the above algorithm is O(log n), and the space complexity is O(1).

You can also use the built-in Python method ‘bin()‘ to calculate the number of set bits in a simple way, like so:

def countBitsToConvert(a: int, b: int) -> int:
    return bin(a^b).count('1')

This method first calculates ‘a XOR b‘ and returns a binary string. Then the ‘count(’1’)‘ method counts the number of ’1’s in the binary string, which is equal to the number of bits required to convert ‘a‘ to ‘b‘. The time complexity is still O(log n) and the space complexity is O(1).

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Coding Interview Essentials interview — then scores it.
📞 Practice Coding Interview Essentials — free 15 min
📕 Buy this interview preparation book: 120 Coding Interview Essentials questions & answers — PDF + EPUB for $5

All 120 Coding Interview Essentials questions · All topics