I was writing an algorithm to compare how many bits are different between 2 numbers using this function
var hammingDistance = function(x, y) {
let result = 0;
while (x !== 0 || y !== 0) {
// This line is incorrect
if (x & 1 !== y & 1) result ;
x = x >> 1;
y = y >> 1;
}
return result;
};
But my result is always 1
less than the correct answer, and it turns our my function is wrong when comparing the left most digit, such as 0011
and 0100
. It returns 2 instead of 3.
https://i.imgur.com/P46RyZr.png
I can use XOR
instead of !==
to get the correct answer. But I'm wondering why?
CodePudding user response:
Your problem is that !==
has a higher precedence than &
. So your condition is actually (x & (1 !== y)) & 1
. Use explicit grouping instead:
if ((x & 1) !== (y & 1)) result ;
It works with ^
because that has a lower precedence than &
.