Skip to content

Commit debe6ea

Browse files
committed
Fix
1 parent bcb286b commit debe6ea

File tree

1 file changed

+17
-10
lines changed

1 file changed

+17
-10
lines changed

src/main/java/com/thealgorithms/conversions/IntegerToEnglish.java

Lines changed: 17 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -41,24 +41,32 @@ private IntegerToEnglish() {
4141
*/
4242
private static String convertToWords(int number) {
4343
int remainder = number % 100;
44-
String result = "";
44+
StringBuilder result = new StringBuilder();
4545

4646
if (remainder <= 20) {
47-
result = BASE_NUMBERS_MAP.get(remainder);
47+
result.append(BASE_NUMBERS_MAP.get(remainder));
4848
} else if (BASE_NUMBERS_MAP.containsKey(remainder)) {
49-
result = BASE_NUMBERS_MAP.get(remainder);
49+
result.append(BASE_NUMBERS_MAP.get(remainder));
5050
} else {
5151
int tensDigit = remainder / 10;
5252
int onesDigit = remainder % 10;
53-
result = String.format("%s %s", BASE_NUMBERS_MAP.get(tensDigit * 10), BASE_NUMBERS_MAP.get(onesDigit)).trim();
53+
String tens = BASE_NUMBERS_MAP.get(tensDigit * 10);
54+
String ones = BASE_NUMBERS_MAP.get(onesDigit);
55+
result.append(tens);
56+
if (!ones.isEmpty()) {
57+
result.append(" ").append(ones);
58+
}
5459
}
5560

5661
int hundredsDigit = number / 100;
5762
if (hundredsDigit > 0) {
58-
result = String.format("%s Hundred%s%s", BASE_NUMBERS_MAP.get(hundredsDigit), result.isEmpty() ? "" : " ", result);
63+
if (result.length() > 0) {
64+
result.insert(0, " ");
65+
}
66+
result.insert(0, String.format("%s Hundred", BASE_NUMBERS_MAP.get(hundredsDigit)));
5967
}
6068

61-
return result != null ? result.trim() : "";
69+
return result.toString().trim();
6270
}
6371

6472
/**
@@ -85,11 +93,10 @@ public static String integerToEnglishWords(int number) {
8593
if (index > 0) {
8694
subResult += " " + THOUSAND_POWER_MAP.get(index);
8795
}
88-
if (!result.isEmpty()) {
89-
result.insert(0, subResult + " ");
90-
} else {
91-
result.append(subResult);
96+
if (result.length() > 0) {
97+
result.insert(0, " ");
9298
}
99+
result.insert(0, subResult);
93100
}
94101
}
95102

0 commit comments

Comments
 (0)