Comments
Your current comments aren't all that helpful, as they are just repeating excactly what the code already told me.
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).
See also this question about counting the number of set bits in an integer.