[LeetCode] Integer to English Words

Question:
Convert a non-negative integer to its English words representation. Given input is guaranteed to be less than 2^31 - 1.

Example 1:

1
2
Input: 123
Output: "One Hundred Twenty Three"

Example 2:

1
2
Input: 12345
Output: "Twelve Thousand Three Hundred Forty Five"

Example 3:

1
2
Input: 1234567
Output: "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"

Example 4:

1
2
Input: 1234567891
Output: "One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One"

Analysis:

To be honest, this question is not that hard. We need to know the logic of these sentences here. You need to know the rules of the counting and can solve it quickly. Let us see how to solve this question.

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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
class Solution {
public String numberToWords(int num) {
if (num == 0) return "Zero";

int billions = num/1000000000;
num %= 1000000000;

int millions = num/1000000;
num %= 1000000;

int thousands = num/1000;
num %= 1000;

StringBuilder string = new StringBuilder();
if (billions > 0)
string.append(helper(billions) + "Billion ");
if (millions > 0)
string.append(helper(millions) + "Million ");
if (thousands > 0)
string.append(helper(thousands) + "Thousand ");
if (num > 0)
string.append(helper(num));

return string.toString().trim();

}

public String helper(int num) {
String[] numbers = {
"", "One ", "Two ", "Three ", "Four ", "Five ", "Six ", "Seven ", "Eight ", "Nine ", "Ten ",
"Eleven ", "Twelve ", "Thirteen ", "Fourteen ", "Fifteen ", "Sixteen ", "Seventeen ", "Eighteen ", "Nineteen "
};

String[] tens = {
"", "", "Twenty ", "Thirty ", "Forty ", "Fifty ", "Sixty ", "Seventy ", "Eighty ", "Ninety "
};

int hundred = num/100;
num %= 100;

StringBuilder string = new StringBuilder();
if (hundred != 0) string.append(numbers[hundred] + "Hundred ");

if (num < 20) {
string.append(numbers[num]);
}
else {
string.append(tens[num/10] + numbers[num%10]);
}

return string.toString();
}
}