/*
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.c++
Given two integers x and y, calculate the Hamming distance.spa
Note:
0 ≤ x, y < 231.code
Example:rem
Input: x = 1, y = 4it
Output: 2io
Explanation:class
1 (0 0 0 1)二进制
4 (0 1 0 0)gc
The above arrows point to positions where the corresponding bits are different.
*/
int hammingDistance(int x, int y) {im
}
* 能够利用异或的特性:相同为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; }