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.
这个题意大致就是 两个数a,b 把两个数转化为2进制数,然后找他们相同位数上的数字是不是不同,这些不同的个数加起来就是汉明距离.
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.
这个题意大致就是 两个数a,b 把两个数转化为2进制数,然后找他们相同位数上的数字是不是不同,这些不同的个数加起来就是汉明距离.
我的做法是这样:
做法1:
int hammingDistance(int x, int y) {
int c = x^y, d = 0;//先用按位异或运算求出c,再计算c中1的个数
while (c)
{
if (c % 2 == 1)
{
d++;
}
c /= 2;
}
return d;
}
做法2:
int hammingDistance(int x, int y) {
int res = 0, exc = x ^ y;
while (exc) {
++res;
exc &= (exc - 1);//这个得用处就是把exc化为二进制后最右边的1变为0;看一共变了多少次,(就有多少个1)//还有个用,判断一个数(x)是否是2的n次方,if( (x&(x-1)) == 0 ) return 1;
}
return res;
}
做法3:
int hammingDistance(int x, int y)
{
if ((x ^ y) == 0) return 0;//看是不是相同的两个数
return (x ^ y) % 2 + hammingDistance(x / 2, y / 2);//运用递归,实际和第一种做法一个意思,
//(x ^ y) % 2 就是一个计数器x,循环一次加次,可能加的是可能是1,hammingDistance(x / 2, y / 2)就是一直调用,直到(x ^ y) == 0,结束就依次跳出循环了,返回 return (x ^ y) % 2 + hammingDistance(x / 2, y / 2);
}
做法4:
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;
}
};