Skip to content

Commit 06699ca

Browse files
committed
Added task 273.
1 parent e971838 commit 06699ca

File tree

2 files changed

+84
-0
lines changed

2 files changed

+84
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
package s0273.integer.to.english.words;
2+
3+
public class Solution {
4+
5+
String[] ones =
6+
new String[] {
7+
"One ", "Two ", "Three ", "Four ", "Five ", "Six ", "Seven ", "Eight ", "Nine "
8+
};
9+
String[] teens =
10+
new String[] {
11+
"Ten ",
12+
"Eleven ",
13+
"Twelve ",
14+
"Thirteen ",
15+
"Fourteen ",
16+
"Fifteen ",
17+
"Sixteen ",
18+
"Seventeen ",
19+
"Eighteen ",
20+
"Nineteen "
21+
};
22+
String[] twenties =
23+
new String[] {
24+
"Twenty ", "Thirty ", "Forty ", "Fifty ", "Sixty ", "Seventy ", "Eighty ", "Ninety "
25+
};
26+
27+
String zero = "Zero";
28+
String hundred = "Hundred ";
29+
String thousand = "Thousand ";
30+
String million = "Million ";
31+
String billion = "Billion ";
32+
33+
public String numberToWords(int num) {
34+
if (num == 0) return zero;
35+
36+
StringBuilder sb = new StringBuilder();
37+
38+
processThreeDigits(sb, num / 1_000_000_000, billion);
39+
processThreeDigits(sb, num / 1_000_000, million);
40+
processThreeDigits(sb, num / 1_000, thousand);
41+
processThreeDigits(sb, num, null);
42+
43+
return sb.toString().trim();
44+
}
45+
46+
private void processThreeDigits(StringBuilder sb, int input, String name) {
47+
int threeDigit = input % 1000;
48+
49+
if (threeDigit > 0) {
50+
if (threeDigit / 100 > 0) {
51+
sb.append(ones[threeDigit / 100 - 1]);
52+
sb.append(hundred);
53+
}
54+
55+
if (threeDigit % 100 >= 20) {
56+
sb.append(twenties[(threeDigit % 100) / 10 - 2]);
57+
if (threeDigit % 10 > 0) {
58+
sb.append(ones[threeDigit % 10 - 1]);
59+
}
60+
} else if (threeDigit % 100 >= 10 && threeDigit % 100 < 20) {
61+
sb.append(teens[threeDigit % 10]);
62+
} else if (threeDigit % 100 > 0 && threeDigit % 100 < 10) {
63+
sb.append(ones[threeDigit % 10 - 1]);
64+
}
65+
66+
if (name != null) {
67+
sb.append(name);
68+
}
69+
}
70+
}
71+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
package s0273.integer.to.english.words;
2+
3+
import static org.hamcrest.CoreMatchers.equalTo;
4+
import static org.hamcrest.MatcherAssert.assertThat;
5+
6+
import org.junit.Test;
7+
8+
public class SolutionTest {
9+
@Test
10+
public void numberToWords() {
11+
assertThat(new Solution().numberToWords(123), equalTo("One Hundred Twenty Three"));
12+
}
13+
}

0 commit comments

Comments
 (0)