Returns the Hamming distance between two integers.
More...
#include <cassert>
#include <iostream>
Returns the Hamming distance between two integers.
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
◆ bitCount()
| uint64_t bit_manipulation::hamming_distance::bitCount |
( |
uint64_t |
value | ) |
|
This function returns the number of set bits in the given number.
- Parameters
-
| value | the number of which we want to count the number of set bits. |
- Returns
- the number of set bits in the given number.
◆ hamming_distance() [1/2]
| uint64_t bit_manipulation::hamming_distance::hamming_distance |
( |
const std::string & |
a, |
|
|
const std::string & |
b |
|
) |
| |
This function returns the hamming distance between two strings.
- Parameters
-
| a | the first string |
| b | the second string |
- Returns
- the number of characters differing between the two strings.
60 assert(a.size() == b.
size());
63 for (
size_t i = 0; i < n; i++) {
64 count += (b[i] != a[i]);
◆ hamming_distance() [2/2]
| uint64_t bit_manipulation::hamming_distance::hamming_distance |
( |
uint64_t |
a, |
|
|
uint64_t |
b |
|
) |
| |
This function returns the hamming distance between two integers.
- Parameters
-
| a | the first number |
| b | the second number |
- Returns
- the number of bits differing between the two integers.
uint64_t bitCount(uint64_t value)
Definition: hamming_distance.cpp:34
◆ main()
Main function.
- Returns
- 0 on exit
104 std::cout <<
"Hamming distance between " << a <<
" and " << b <<
" is "
static void test()
Function to the test hamming distance.
Definition: hamming_distance.cpp:75
uint64_t hamming_distance(uint64_t a, uint64_t b)
Definition: hamming_distance.cpp:51
◆ test()
Function to the test hamming distance.
- Returns
- void
76 assert(bit_manipulation::hamming_distance::hamming_distance(11, 2) == 2);
77 assert(bit_manipulation::hamming_distance::hamming_distance(2, 0) == 1);
78 assert(bit_manipulation::hamming_distance::hamming_distance(11, 0) == 3);
80 assert(bit_manipulation::hamming_distance::hamming_distance(
"1101",
82 assert(bit_manipulation::hamming_distance::hamming_distance(
"1111",
84 assert(bit_manipulation::hamming_distance::hamming_distance(
"0000",
87 assert(bit_manipulation::hamming_distance::hamming_distance(
"alpha",
89 assert(bit_manipulation::hamming_distance::hamming_distance(
"abcd",
91 assert(bit_manipulation::hamming_distance::hamming_distance(
"dcba",