I have suggestion for you.
- I suggest that you extract the length of the
binx
and biny
in two variables, so you can use them instead of recalling the java.lang.String#length
each time.
String binx = Integer.toBinaryString(x);
int binxLength = binx.length();
String biny = Integer.toBinaryString(y);
int binyLength = biny.length();
//[...]
if (binxLength > binyLength) {
//[...]
}
//[...]
- You can use the method
java.lang.String#repeat
(java 11+) to repeat the zeros
sb.append("0".repeat(dif));
- I suggest that you make a method to repeat the zeros.
private String repeatZeros(int nb) {
return "0".repeat(nb);
}
- In my opinion, the
dif
variable is useless, you can inline it.
sb.append(repeatZeros(binxLength - binyLength));
- Since you are not concatenating the
String
in a loop, instead of using the StringBuilder
, you can concat them directly.
if (binxLength > binyLength) {
biny = repeatZeros(binxLength - binyLength) + biny;
} else if (binyLength > binxLength) {
binx = repeatZeros(binyLength - binxLength) + binx;
}
- I suggest that you create a method to pad the binary string.
private String padLeftWithZeros(String str, int length) {
return repeatZeros(length) + str;
}
public int hammingDistance(int x, int y) {
//[...]
if (binxLength > binyLength) {
biny = padLeftWithZeros(biny, (binxLength - binyLength));
} else if (binyLength > binxLength) {
binx = padLeftWithZeros(binx, (binyLength - binxLength));
}
//[...]
}
- I suggest that you extract the distance in a method and return the result.
public int hammingDistance(int x, int y) {
//[...]
return calculateHammingDistance(binx, binxLength, biny);
}
private int calculateHammingDistance(String binx, int binxLength, String biny) {
int dist = 0;
for (int i = 0; i < binxLength; i++) {
if (binx.charAt(i) != biny.charAt(i)) {
dist++;
}
}
return dist;
}
Refactored code
public int hammingDistance(int x, int y) {
String binx = Integer.toBinaryString(x);
int binxLength = binx.length();
String biny = Integer.toBinaryString(y);
int binyLength = biny.length();
if (binxLength > binyLength) {
biny = padLeftWithZeros(biny, (binxLength - binyLength));
} else if (binyLength > binxLength) {
binx = padLeftWithZeros(binx, (binyLength - binxLength));
}
return calculateHammingDistance(binx, binxLength, biny);
}
private String padLeftWithZeros(String str, int length) {
return repeatZeros(length) + str;
}
private String repeatZeros(int nb) {
return "0".repeat(nb);
}
private int calculateHammingDistance(String binx, int binxLength, String biny) {
int dist = 0;
for (int i = 0; i < binxLength; i++) {
if (binx.charAt(i) != biny.charAt(i)) {
dist++;
}
}
return dist;
}