Created
December 3, 2018 07:01
-
-
Save XcqRomance/4426b970611a1b1b72e8ed6de57839e3 to your computer and use it in GitHub Desktop.
位1的个数
This file contains hidden or 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
// 位1的个数, | |
int hammingWeight(uint32_t n) { | |
int count = 0; | |
while (n) { | |
++count; | |
n = (n-1)&n; | |
} | |
return count; | |
} | |
int hammingWeight2(uint32_t n) { | |
int count = 0; | |
unsigned int flag = 1; | |
while (flag) { | |
if (flag&n) { | |
++count; | |
} | |
flag = flag<<1; | |
} | |
return count; | |
} | |
// 汉明距离 | |
int hammingDistance(int x, int y) { | |
int n = x^y; | |
return hammingWeight(n); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment