/* 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. */ int hammingDistance(int x, int y) {
}
###题意: 输入两个int,求这两个数的二进制数的不同的位的个数。
###办法一: * 可以利用异或的特性:相同为0,不同为1。把两数异或,再判断结果有几个1。
* 怎么判断int中有几个1?
* 可以对这个数除2运算,并记录模2为1的个数,直至此数变到0。也就是模拟了转二进制数的过程。
###办法二: * 先异或。
* 如何判断有几个1?
* 右移一位,再左移一位,如果不等于原数,就是有一个1。同样模拟了转二进制数的过程。
* 除2即右移一位。
###办法三: * 先异或。
* 如何判断有几个1?
while(n) {
c++;
n=n&(n-1);
}
n&(n-1)就是把n的最未的1变成0。
#include <stdio.h>
int hammingDistance(int x, int y) {
int r = x ^ y;
int cnt = 0;
while (r > 0) {
if (r%2 == 1) {
cnt ++;
}
r = r/2;
}
return cnt;
}
int hammingDistance2(int x, int y) {
int r=x^y;
int cnt = 0;
while (r) {
if ((r>>1)<<1 != r) {
cnt ++;
}
r >>= 1;
}
return cnt;
}
int hammingDistance3(int x, int y) {
int r=x^y;
int cnt=0;
while (r) {
cnt ++;
r=r&(r-1);
}
return cnt;
}
int main(int argc, char *argv[])
{
printf("%d\n", hammingDistance3(1,4));
return 0;
}