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.
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 train of thought:
Step 1:
什么是hamming distance?
hamming distance在discrete math里也学过,先复习一下concept:
它表示两个(相同长度)字对应位不同的数量,我们以d(x,y)表示两个字x,y之间的汉明距离。对两个字符串进行异或运算,并统计结果为1的个数,那么这个数就是hamming distance。
最小hamming distance
1. 用于检错,可检测e个位置的错误:d>=e+1;
2. 用于纠错,可纠错t个位置的错误:d>=2t+1;
3. 检错+纠错,纠正t个错,检测e个错:d>=e+t+1;
这里e>t,这种检错纠错方式结合的情况同上述两个情况类似。当码字出现t个或者小于t个错时,系统按照纠错方式工作。当码字出现超过t个错而小于等于e个错时,系统按照检错方式工作。
step 2:
十进制转二进制
将十进制数进行短除,能整除记0,不能整除记1,直到最后被除数为1
step 3:
如何保存二进制数?
因为用C/C++,我第一想到的就是数组,一位一位存嘛,比较起来也方便,后来看题解觉得自己真是愚蠢了。
step 4:
如何逐位比较?
既然用了数组,那当然是笨笨地一位一位比较,多出来的再判断,如果是1就计入总数,嗨,这个办法可真是笨呀!
- My solution:
int hammingDistance(int x, int y) {
int i=0,j=0,k=0,count=0;
int a[40],b[40];
while(x>=1)
{
if(x%2==1) a[i]=1;
else a[i]=0;
x=x/2;
i++;
}
i=i-1;
while(y>=1)
{
if(y%2==1) b[j]=1;
else b[j]=0;
y=y/2;
j++;
}
j=j-1;
while(k<=i && k<=j)
{
if(a[k]!=b[k]) count++;
k++;
}
k=k-1;
while(i>k)
{
k++;
if(a[k]==1) count++;
}
while(j>k)
{
k++;
if(b[k]==1) count++;
}
return count;
}
Run time: 3ms
- Better Solution
class Solution {
public:
int hammingDistance(int x, int y) {
int dist = 0, n = x ^ y;
while (n) {
++dist;
n &= n - 1;
}
return dist;
}
};
比起我的笨办法,这个解法真的很简洁了,用到了bit manipulation也就是位运算。
一共是五种运算:与,或,异或,左移,右移
1. 按位与运算(&)
1&1为 1,0&0为 0,1&0也为 0
C语言中按位与运算是按照数据的内部二进制形式进行运算的。若是两个负数,则是按二进制补码形式进行按位与。所得结果若用有符号整型变量存储,则内部形式仍看作二进制补码。如果用格式符%d输出,输出结果为十进制真值(不应该称为十进制原码)。
e.g. input 7 & 15
0000 0111-> +7
0000 1111 ->+15
0000 0111 ->+7
output 7
2. 按位或运算(|)
3. 按位异或运算(^)
4. 取反运算(~)
5. 左移运算(<<)
6. 右移运算(>>)
懒了,,有用到再说吧。。