#include <stdio.h> | |||||
int countBits(int); | |||||
int hammingDistance(int x, int y) { | |||||
return countBits(x ^ y); | |||||
} | |||||
int countBits(int v) { | |||||
int c; | |||||
for (c = 0; v; v >>= 1) { | |||||
c += v & 1; | |||||
} | |||||
return c; | |||||
} | |||||
int main() { | |||||
printf("Expected: 2\n"); | |||||
printf("Got: %d\n", hammingDistance(1, 4)); | |||||
return 0; | |||||
} |
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. |
#!/bin/bash | |||||
gcc -o main main.c | |||||
./main | |||||
rm main |