Files
test/puzzles/interviews/training/hamming_distance.cpp
2019-03-03 23:09:42 +00:00

37 lines
860 B
C++

/*
LeetCode
461. Hamming Distance
Easy
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 ≤ x, y < 231.
Example:
Input: x = 1, y = 4
Output: 2
Explanation:
1 (0 0 0 1)
4 (0 1 0 0)
↑ ↑
The above arrows point to positions where the corresponding bits are different.
*/
class Solution {
public:
int hammingDistance(int x, int y) {
unsigned z = x ^ y;
z = (z & 0x55555555) + ((z >> 1) & 0x55555555);
z = (z & 0x33333333) + ((z >> 2) & 0x33333333);
z = (z & 0x0f0f0f0f) + ((z >> 4) & 0x0f0f0f0f);
z = (z & 0x00ff00ff) + ((z >> 8) & 0x00ff00ff);
z = (z & 0x0000ffff) + ((z >> 16) & 0x0000ffff);
return z;
}
};