Javascript one line solution


  • 21
    /**
     * @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;
    };
    

  • 0
    J

    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)
    	const zeroFillNumberString = (padding, input) => "0".repeat(padding) + input
    	
    	let hammingDistance = 0
    	
    	x = numberToBinaryString(x)
    	y = numberToBinaryString(y)
    	
    	const padding = Math.abs(x.length - y.length)
    	
    	if(x.length < y.length)
    		x = zeroFillNumberString(padding, x)
    	else
    		y = zeroFillNumberString(padding, y)
    	
    	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.


Log in to reply
 

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