两个整数之间的汉明距离指的是这两个数字对应二进制位不同的位置的数目。
给出两个整数 x
和 y
,计算它们之间的汉明距离。
注意:
0 ≤ x
, y
< 231.
示例:
输入: x = 1, y = 4 输出: 2 解释: 1 (0 0 0 1) 4 (0 1 0 0) ↑ ↑ 上面的箭头指出了对应二进制位不同的位置。
C#代码
public class Solution {
public int HammingDistance(int x, int y) {
var byte1 = Convert.ToString(x, 2);
var byte2 = Convert.ToString(y, 2);
int diffLength = byte1.Length - byte2.Length;
string str = "";
for (int i = 0; i < Math.Abs(diffLength); i++)
str += '0';
if (diffLength > 0)
byte2 = str + byte2;
if (diffLength < 0)
byte1 = str + byte1;
int num = 0;
for (int i = 0; i < byte1.Length; i++)
{
if (byte1[i] != byte2[i])
num += 1;
}
return num;
}
}