# Javascript one line solution

• ``````/**
* @param {number} x
* @param {number} y
* @return {number}
*/
var hammingDistance = function(x, y) {
return (x ^ y).toString(2).replace(/0/g, '').length;
};``````

• That's a nice use of the length property

For reference, here are a couple other one-line JavaScript solutions, along with the above, as well as their runtimes:

``````// 135ms 16.23%
return [... (x ^ y).toString (2)].map ((x) => parseInt (x)) . reduce ((acc, x) => acc + x)

//125ms 27.36%
return (x ^ y).toString (2) . replace (/0/g, '') . length

// 105ms 67.88%
return [... (x ^ y).toString (2)].filter ((c) => c === '1') . length``````

• Does this solution work with negative integers? I think you may need to coerce the arguments to be unsigned by using a right logical shift (>>>).

``````return ((x ^ y) >>> 0).toString(2)...
``````

• ``````var hammingDistance = function (x, y) {
return (x ^ y).toString(2).split('').filter(num => num === "1").length;
};
``````

this do well too.

• Easier to understand even for beginners

``````    var p = y^x; // Finding XOR is the best shortcut
var a = p.toString(2);

var leng1 = a.length;

var xx = 0;
var pp = 0;

for (i = 0; i < leng1; i++) {
if (a.charAt(i) == 1)
xx = xx+1;
else
pp = pp+1;
}

return xx;
};
``````

• This was my first attempt. Definitely not an optimal solution. It's always interesting to compare first attempts to attempts done on iteration.

``````/**
* @param {number} x
* @param {number} y
* @return {number}
*/
var hammingDistance = function(x, y) {

const numberToBinaryString = input => (input >>> 0).toString(2)

let hammingDistance = 0

x = numberToBinaryString(x)
y = numberToBinaryString(y)

const padding = Math.abs(x.length - y.length)

if(x.length < y.length)
else

for(i in x)
hammingDistance += x[i] ^ y[i]

return hammingDistance

}
``````

Edit: In the future, I will avoid looking at solutions before submitting my working solution. I would have loved to see how I optimized my approach.

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.