Hamming Distance: Difference between revisions
Jump to navigation
Jump to search
Line 9: | Line 9: | ||
<syntaxhighlight lang='java'> | <syntaxhighlight lang='java'> | ||
public static int hammingDistance(int i1, int i2) { | public static int hammingDistance(int i1, int i2) { | ||
int | int differences = 0; | ||
int xor = i1 ^ i2; | int xor = i1 ^ i2; | ||
while(xor > 0) { | while(xor > 0) { | ||
differences += xor & 1; | |||
xor >>= 1; | xor >>= 1; | ||
} | } | ||
return | return differences; | ||
} | } | ||
</syntaxhighlight> | </syntaxhighlight> | ||
Also see: {{Internal|Java_Language#Integer_Bitwise_XOR_.5E|Integer Bitwise XOR <tt>^</tt> in Java}} | Also see: {{Internal|Java_Language#Integer_Bitwise_XOR_.5E|Integer Bitwise XOR <tt>^</tt> in Java}} |
Latest revision as of 21:52, 24 October 2021
External
Internal
Overview
The Hamming distance between two string of equal length is the number of positions at which the corresponding symbols are different. In other words, it measures the minimum number of substitutions required to change on string into the other, or the minimum number of errors that could have transformed one string into the other.
Implementations
Hamming Distance between Two Integers in Java
public static int hammingDistance(int i1, int i2) {
int differences = 0;
int xor = i1 ^ i2;
while(xor > 0) {
differences += xor & 1;
xor >>= 1;
}
return differences;
}
Also see: