題目
難度:easy
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Given two integers x and y, calculate the Hamming distance.
Note:
0 ≤ x, y <2^31
Example:
Input: x = 1, y = 4
Output: 2
Explanation:
1 (0 0 0 1)
4 (0 1 0 0)
↑ ↑
The above arrows point to positions where the corresponding bits are different.
知識(shí)點(diǎn)
漢明距離是使用在數(shù)據(jù)傳輸差錯(cuò)控制編碼里面的绣硝,漢明距離是一個(gè)概念,它表示兩個(gè)(相同長(zhǎng)度)字對(duì)應(yīng)位不同的數(shù)量撑刺,我們以d(x,y)表示兩個(gè)字x,y之間的漢明距離鹉胖。對(duì)兩個(gè)字符串進(jìn)行異或運(yùn)算,并統(tǒng)計(jì)結(jié)果為1的個(gè)數(shù)猜煮,那么這個(gè)數(shù)就是漢明距離次员。
第一次解法
/**
* @param {number} x
* @param {number} y
* @return {number}
*/
var hammingDistance = function(x, y) {
return (x ^ y).toString(2).split('').filter(num => num === "1").length;
};