mirror of
https://github.com/TheAlgorithms/C-Plus-Plus.git
synced 2026-02-11 14:36:25 +08:00
46 lines
1.2 KiB
C++
46 lines
1.2 KiB
C++
/**
|
|
* @file
|
|
* @brief Returns the [Hamming
|
|
* distance](https://en.wikipedia.org/wiki/Hamming_distance) between two
|
|
* integers
|
|
*
|
|
* @details
|
|
* To find hamming distance between two integers, we take their xor, which will
|
|
* have a set bit iff those bits differ in the two numbers.
|
|
* Hence, we return the number of such set bits.
|
|
*
|
|
* @author [Ravishankar Joshi](https://github.com/ravibitsgoa)
|
|
*/
|
|
|
|
#include <iostream> /// for io operations
|
|
|
|
unsigned int bitCount(unsigned int value) {
|
|
unsigned int count = 0;
|
|
while (value) { // until all bits are zero
|
|
if (value & 1) { // check lower bit
|
|
count++;
|
|
}
|
|
value >>= 1; // shift bits, removing lower bit
|
|
}
|
|
return count;
|
|
}
|
|
|
|
unsigned int hamming_distance(int a, int b) {
|
|
if (a < 0 || b < 0) {
|
|
throw "Both arguments must be >=0 for finding hamming distance.";
|
|
}
|
|
return bitCount(a ^ b);
|
|
}
|
|
|
|
/**
|
|
* @brief Main function
|
|
* @returns 0 on exit
|
|
*/
|
|
int main() {
|
|
int a = 11; // 1011 in binary
|
|
int b = 2; // 0010 in binary
|
|
|
|
std::cout << "Hamming distance between " << a << " and " << b << " is "
|
|
<< hamming_distance(a, b) << std::endl;
|
|
}
|