Created
November 7, 2024 05:42
-
-
Save sAVItar02/04d3dfb1497767d309b2e3c51e5e1057 to your computer and use it in GitHub Desktop.
Hamming Distance
This file contains 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} | |
*/ | |
var hammingDistance = function(x, y) { | |
let xor = x ^ y; | |
let count = 0; | |
while (xor != 0) { | |
xor &= xor - 1; | |
count++; | |
} | |
return count; | |
}; | |
// xor operation returns returns 0 if both bits are same and 1 otherwise | |
// x xor y will give return 1 where bits differ, so we have to count all the set bits in x xor y | |
// x & (x-1) changes the least significant set bit of a number, we do this till we get 0 | |
// increase count everytime we do (x & (x-1)) which is in this case (xor & (xor -1)) | |
// return count | |
// Time: O(1) | |
// Space: O(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment