http://bookshadow.com/weblog/2016/12/18/leetcode-hamming-distance/
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 ≤
0 ≤
x
, y
< 231.
Example:
https://leetcode.com/problems/hamming-distance/discuss/94698/Java-1-Line-Solution-%3AD
What does come to your mind first when you see this sentence
"corresponding bits are different"
? Yes, XOR
! Also, do not forget there is a decent function Java provided: Integer.bitCount()
~~~public class Solution {
public int hammingDistance(int x, int y) {
return Integer.bitCount(x ^ y);
}
https://leetcode.com/problems/hamming-distance/discuss/94713/Java-solution public int hammingDistance(int x, int y) {
int xor = x ^ y, count = 0;
while (xor != 0) {
xor &= (xor - 1);
count++;
}
return count;
}
https://leetcode.com/problems/hamming-distance/discuss/94705/My-C%2B%2B-solution-using-bit-manipulation int hammingDistance(int x, int y) {
int dist = 0, n = x ^ y;
while (n) {
++dist;
n &= n - 1;
}
return dist;
}
https://leetcode.com/problems/hamming-distance/discuss/94693/Java-3-Line-Solutionpublic int hammingDistance(int x, int y) {
int xor = x ^ y, count = 0;
for (int i=0;i<32;i++) count += (xor >> i) & 1;
return count;
}
http://blog.csdn.net/zhouziyu2011/article/details/53726977- public int hammingDistance(int x, int y) {
- int res = x ^ y;
- int count = 0;
- for (int i = 0; i < 32; i++) {
- if ((res & 1) != 0)
- count++;
- res >>= 1;
- }
- return count;
- }