Javascript Solution


  • 0
    H

    Solution:

    /**
     * @param {number} x
     * @param {number} y
     * @return {number}
     */
    function hammingDistance(x, y) {
    	return ((x ^ y).toString(2).match(/1/g) || '').length;
    }
    

    Breakdown:

    1. You can get the binary value of a number by doing .toString() on it. The first parameter to .toString() is the base. Binary is base 2, so doing x.toString(2) gets the binary value of x.
    2. Hamming distance is the number of positions where the bit between x and y are different. That means you must compare the binaries by iteration and count how many times x[i] !== y[i].
    3. In Javascript, the bitwise operation for XOR is ^. XOR compares two binaries and sets 1 for each bit where one of them is 1. This means we can count the number of 1s in the XOR'd binary instead of comparing two binaries by iteration.
    4. You can count the number of 1s in a string with the .match() by doing a Regular Expression match with the global flag: /1/g. If there are no matches, it returns null. Hence the (x.match(/1/g) || '')

Log in to reply
 

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