1.
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.
my answer:
class Solution {
public:
int hammingDistance(int x, int y) {
int a[31],b[31];
int c=0;
for(int i=0;i<31;i++)
{
if(x%2!=0)
{
a[i]=1;
x=x/2;
}
else
{a[i]=0;
x=x/2;
}
if(y%2!=0)
{
b[i]=1;
y=y/2;
}
else
{b[i]=0;
y=y/2;
}
if(a[i]!=b[i])
c++;
}
return c;
}
};
答本题之前需要知道汉明距离的概念:
汉明距离是使用在数据传输差错控制编码里面的,汉明距离是一个概念,它表示两个(相同长度)字对应位不同的数量,我们以d(x,y)表示两个字x,y之间的汉明距离。对两个字符串进行异或运算,并统计结果为1的个数,那么这个数就是汉明距离。
汉明距离是以理查德·卫斯里·汉明的名字命名的。在信息论中,两个等长字符串之间的汉明距离是两个字符串对应位置的不同字符的个数。换句话说,它就是将一个字符串变换成另外一个字符串所需要替换的字符个数。例如:
1011101 与 1001001 之间的汉明距离是 2。
2143896 与 2233796 之间的汉明距离是 3。
"toned" 与 "roses" 之间的汉明距离是 3。
在本题中我遇到的问题:
1.理解错汉明距离的概念,误认为是2进制数,求长度的距离。
2.把%和/搞混乱。
3.把问题想复杂化。