forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHammingDistance.java
32 lines (25 loc) · 913 Bytes
/
HammingDistance.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package com.thealgorithms.others.cn;
public final class HammingDistance {
private HammingDistance() {
}
private static void checkChar(char inChar) {
if (inChar != '0' && inChar != '1') {
throw new IllegalArgumentException("Input must be a binary string.");
}
}
public static int compute(char charA, char charB) {
checkChar(charA);
checkChar(charB);
return charA == charB ? 0 : 1;
}
public static int compute(String bitsStrA, String bitsStrB) {
if (bitsStrA.length() != bitsStrB.length()) {
throw new IllegalArgumentException("Input strings must have the same length.");
}
int totalErrorBitCount = 0;
for (int i = 0; i < bitsStrA.length(); i++) {
totalErrorBitCount += compute(bitsStrA.charAt(i), bitsStrB.charAt(i));
}
return totalErrorBitCount;
}
}