Skip to content

Instantly share code, notes, and snippets.

@yigger
Created March 1, 2017 04:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yigger/9917e75c14324136803593c5f00ba01f to your computer and use it in GitHub Desktop.
Save yigger/9917e75c14324136803593c5f00ba01f to your computer and use it in GitHub Desktop.
/*
计算汉明距离,
eg:x = 4,y = 3
x:0100
y:0011
汉明距离 = 3
算法:
先算x^y = 0111
这里只需要判断有几个1,那么汉明距离就是多少
技巧
先右移一位 0011 再左移 0110,判断这个数是否等于 0111
*/
int hammingDistance(int x, int y) {
int res=x^y;
int dis=0;
while(res){
if((res>>1)<<1 != res) {
++dis;
}
res>>=1;
}
return dis;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment