# Count bits that differ between integers X and Y

I'm trying to solve the following problem :

You are given two integers, X and Y. Calculate the number of bits that will be changed in order to convert integer X to integer Y.

Here is my solution

function findNumberOfBits(x, y){
var bitCount = 0;
var z = x ^ y;  //XOR x and y
while (z !== 0){
bitCount += z & 1;
z = z >> 1;  //shift Z by 1 bit to the right
//console.log("bitCount ", bitCount);
//console.log(z);
}
return bitCount;
}

var result = findNumberOfBits(12, 16);

1. Is this correct? My tests seem to say yes, but just to make sure.
2. Is this the most efficient way to write it in JavaScript?

To improve them, think about why you are doing what you are doing, and what the result represents. For example:

var z = x ^ y; //XOR x and y

Right, so ^ is bitwise xor. But why are you doing this? What is z after this operation?

var z = x ^ y;  // set bits in z that are different in x and y to 1.


This is a bit more helpful (but you can improve on the phrasing if you want).

Misc

• Your indentation is off a bit.
• remove debug statements

If you do this, your code might look like this:

function findNumberOfBits(x, y) {
var bitCount = 0;
var z = x ^ y;  // set bits in z that are different in x and y to 1.
while (z !== 0) { // not all bits are 0
bitCount += z & 1; //  add least significant bit
z = z >> 1;  // iterate over z; set next bit as lsb
}
return bitCount;
}


The comments might be a bit much (you can remove some if you want), but they are not just repeating the code.

Is this correct? My tests seem to say yes, but just to make sure.

Looks good to me.

Is this the most efficient way to write it in JavaScript?

If your code should work platform-independent, probably. Otherwise, no. You need the xor, but to count the number of set bits in the result, there might be better approaches.

What you are calculating is called the hamming distance, and here you can see some efficient implementations for the hamming weight (the count of set bits).

Your solution seems good, but your comments aren't helpful (as tim stated). The explain the use of the ^ and >> operator. I think the intention is good, but these comments aren't helpful to you or to anyone that already knows what these operator do. You should remove them and assume the next developper who will go through your code will go check on internet to find the signification of these operators.