Created
January 23, 2020 17:27
-
-
Save crates/bd2a3b77a369760228c72a7d97570e8c to your computer and use it in GitHub Desktop.
Calculate the Hamming Distance between two integers (LeetCode Question)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param {number} x | |
* @param {number} y | |
* @return {number} | |
*/ | |
const hammingDistance = function(x, y) { | |
let distance = 0; | |
let xor = x ^ y; // bitwise operation calculates the xor | |
while (xor > 0) { | |
distance++; | |
xor &= xor - 1; // clear flags | |
} | |
return distance; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment