Interview Question: The Number of Bits Required to Convert One Integer to Another (C/C++ function)


The question is: how many bits are required to change if we want to convert a integer to another? The problem is from [Cracking the Coding Interview].

This may seem complicated at first but it is actually very simple to implement. We have just to count the number of different bits for each position and sum them up. If the bits are different, the binary XOR will result in one.

The C/C++ function as follows gives the solution to it. Please note that other solutions exist but not as elegant as this one and may require additional condition checks (other than *for loop*).

1
2
3
4
5
6
7
int getNumberOfBitsToChange(int a, int b) {
    int ans = 0;
    for (int c = a ^ b; c != 0; c >>= 1) {
        ans += c & 1;
    }
    return ans;
}
int getNumberOfBitsToChange(int a, int b) {
    int ans = 0;
    for (int c = a ^ b; c != 0; c >>= 1) {
        ans += c & 1;
    }
    return ans;
}

Shift one position to the right each iteration and sum up the difference for the rightmost digit (least significant).

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
193 words
Last Post: How to Use VBScript to Delete Duplicate Excel Rows with Another Less Column Value
Next Post: Tutorial: How to Write a Java Date Class (Basic OOP Concept)

The Permanent URL is: Interview Question: The Number of Bits Required to Convert One Integer to Another (C/C++ function)

Leave a Reply