461. Hamming Distance
In this article we are going through the Leet Code Hamming Distance problem. We are given 2 integer numbers and we are told to find the distance from the bits that differ from each other. A good way to formulate the answer is first write the bits of each byte.
Here we have a 4 byte representation. We are being asked to count the distance by marking the position. Starting form the less significant bit we see that 1 and 1 are same but moving one position to left 1 and 0 is not the same. The rest are all the same. Therefore, the hamming distance is 1.
Using XOR Bitwise Operator
If we use the Xor bitwise operator for the the opposite bits will get 1 and for same will get 0. This solution is pefect since we can generate a 4 bits where the 1 mark the positions we looking for. Thus, we just return the number of 1's as the hamming distance.
/**
* @param {number} x
* @param {number} y
* @return {number}
*/
var hammingDistance = function (x, y) {
let byte = Array.from((x ^ y).toString(2).padStart(4, 0))
let hammingDistance = 0
for (let bit of byte) {
if (bit === "1") {
hammingDistance += 1
}
}
return hammingDistance
};