Commit 7fc51633 authored by Milica Zivkov's avatar Milica Zivkov

result of session 2

parent 5dba94f5
...@@ -44,21 +44,11 @@ public class NumberToWords { ...@@ -44,21 +44,11 @@ public class NumberToWords {
public static String convert(int number) { public static String convert(int number) {
if (number >= 1000) { if (number >= 1000) {
String description = units.get(number / 1000) + DELIMITER + "thousand"; return getDescription(number, 1000, "thousand");
if (number % 1000 == 0) {
return description;
} else if (number % 1000 < 100) {
return description + " and " + convert(number % 1000);
}
return description + DELIMITER + convert(number % 1000);
} }
if (number >= 100) { if (number >= 100) {
String description = units.get(number / 100) + DELIMITER + "hundred"; return getDescription(number, 100, "hundred");
if (number % 100 == 0) {
return description;
}
return description + " and " + convert(number % 100);
} }
if (number >= 20) { if (number >= 20) {
...@@ -71,4 +61,18 @@ public class NumberToWords { ...@@ -71,4 +61,18 @@ public class NumberToWords {
return units.get(number); return units.get(number);
} }
private static String getDescription(int number, int treshold, String thousand) {
String description = convert(number / treshold) + DELIMITER + thousand;
if (number % treshold == 0) {
return description;
} else if (number % treshold < treshold / 10) {
return description + " and " + convert(number % treshold);
}
return description + getDelimiter(treshold) + convert(number % treshold);
}
private static String getDelimiter(int i) {
return i >= 1000 ? DELIMITER : i >= 100 ? " and " : "";
}
} }
...@@ -30,6 +30,9 @@ public class NumberToWordsShould { ...@@ -30,6 +30,9 @@ public class NumberToWordsShould {
assertThat(NumberToWords.convert(1001), is("one thousand and one")); assertThat(NumberToWords.convert(1001), is("one thousand and one"));
assertThat(NumberToWords.convert(1101), is("one thousand one hundred and one")); assertThat(NumberToWords.convert(1101), is("one thousand one hundred and one"));
assertThat(NumberToWords.convert(9999), is("nine thousand nine hundred and ninety nine")); assertThat(NumberToWords.convert(9999), is("nine thousand nine hundred and ninety nine"));
assertThat(NumberToWords.convert(10000), is("ten thousand"));
assertThat(NumberToWords.convert(99099), is("ninety nine thousand and ninety nine"));
assertThat(NumberToWords.convert(386004), is("three hundred eighty six thousand and four"));
} }
} }
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment