Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interview question: Number of bit swaps required to convert one integer to another

A friend of mine was asked this question in an interview. I wasn't able to figure out a solution to this. Question -

Write a function to calculate the number of bit swaps required to convert one integer to other.

like image 806
user450090 Avatar asked Nov 08 '10 00:11

user450090


2 Answers

The bit operation which can be used to figure out which bits are different is xor. Each 1 in the xor value will tell the different bit between the two integers.

int getBitSwapCount(int x, int y) {
    int count = 0;
    for(int z = x^y; z!=0; z = z>> 1) {
        count += z & 1;
    }
    return count; 
}
like image 156
Tushar Gupta Avatar answered Sep 21 '22 07:09

Tushar Gupta


Interview questions aren't only about solutions, they're also (and this is generally even more important that finding a solution) giving you the opportunity to show how you would tackle a novel problem such as this. How would you start on this ? Is there any further information you'd like to know to help you solve it ? Are there any standard functions (in any commonly-used programming language) you'd like to use ?

Give us your best shot, we'll play the interviewer(s) and prompt as you go ...

like image 39
High Performance Mark Avatar answered Sep 24 '22 07:09

High Performance Mark