Created
March 1, 2017 04:37
-
-
Save yigger/9917e75c14324136803593c5f00ba01f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
计算汉明距离, | |
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