The Hamming distance between two integers is the number of positions at which the corresponding bits are different.less
Given two integers x and y, calculate the Hamming distance.
漢明距離是兩個字符串對應位置的不一樣字符的個數,這裏指二進制的不一樣位置code
Input: x = 1, y = 4 Output: 2 Explanation: 1 (0 0 0 1) 4 (0 1 0 0) ↑ ↑
var hammingDistance = function(x, y) { return (x^y).toString(2).replace(/0/g, "").length };
先將X,y進行異位或運算再轉化成二進制而後把0去掉算出長度ip
Runtime: 76 ms, faster than 18.42% of JavaScript online submissions for Hamming Distance.
Memory Usage: 33.8 MB, less than 40.96% of JavaScript online submissions for Hamming Distance.
var hammingDistance = function(x, y) { let ones = 0; let z = x ^ y; while (z) { if (z & 1) { ones += 1; } z = z >> 1; } return ones; };
先算出不一樣位數,而後用右移運算符算出能右移幾回來獲取距離字符串
Runtime: 60 ms, faster than 89.17% of JavaScript online submissions for Hamming Distance. Memory Usage: 34 MB, less than 6.03% of JavaScript online submissions for Hamming Distance.