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
< 231.
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.
思路:
汉明距离就是求相对应二进制位数之间不同的位数。由此很容易想到异或操作符^ (相同位得0,不同位得1)。 之后,只需要统计异或得到的结果中二进制中1的位数即可。
统计结果中二进制位中1的个数思路是:与1进行安慰与,如果所得结果为1,那么证实二进制位为1. 然后将结果右移一位继续循环,直到结果为0为止。
代码如下:
function hanming(x, y) { var num = x ^ y; var result = 0; while ( num > 0) { if(num & 1) { result++; } num = num >> 1; } return result; } var a = hanming(1,4); console.log(a);