Javascript one line solution


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

  • 2
    F

    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

  • 0
    P

    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)...
    

    See here: https://stackoverflow.com/questions/9939760/how-do-i-convert-an-integer-to-binary-in-javascript/16155417#16155417


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

    this do well too.


  • 0
    H

    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;
    };
    

Log in to reply
 

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