Integer to English Words (LeetCode 273): Solution and Explanation
Spell a non-negative integer in English words with single spaces and no "and": 123 becomes "One Hundred Twenty Three" and 1234567 becomes "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven".
Intuition
Look at how you read a big number aloud: you read it comma group by comma group. 1,234,567 is "one million", "two hundred thirty four thousand", "five hundred sixty seven".
Every group is a number from 0 to 999, and it is spoken the same way no matter where it sits. Only the scale word after it changes: nothing, Thousand, Million, Billion.
So the whole problem reduces to one helper that speaks a number below 1000, plus a loop that peels groups off the right with % 1000 and // 1000. Because the loop sees the units group first, each group's words go in front of what you already have.
Approach: Comma groups with a below-1000 helper
- If
numis 0, return"Zero". - Keep three word tables: the words for 0 to 19, the tens words (Twenty to Ninety), and the scales (none, Thousand, Million, Billion).
- Loop while
num > 0: letgroup = num % 1000. If it is not 0, convert it: hundreds digit plusHundred, then a tens word if the remainder is 20 or more, then the word for what is left below 20. Add the scale word and prepend these words to the result. - Divide
numby 1000 and move to the next scale. - Join the words with single spaces.
Step-by-step example
num = 123
- 123 is not 0, so start the group loop.
- group = 123 % 1000 = 123, with no scale word.
- Hundreds digit 1 gives
One Hundred, leaving 23. - 23 is at least 20, so the tens digit 2 gives
Twenty, leaving 3. - 3 gives
Three. PrependOne Hundred Twenty Threeto the empty result. - num //= 1000 is 0, so the loop ends. Answer:
"One Hundred Twenty Three".
Code: Python, Java, C++
1class Solution:
2 BELOW_20 = ["", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"]
3 TENS = ["", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"]
4 SCALES = ["", "Thousand", "Million", "Billion"]
5
6 def numberToWords(self, num: int) -> str:
7 if num == 0:
8 return "Zero"
9 result = []
10 i = 0
11 while num > 0:
12 group = num % 1000
13 if group > 0:
14 words = self.chunk(group)
15 if self.SCALES[i]:
16 words.append(self.SCALES[i])
17 result = words + result
18 num //= 1000
19 i += 1
20 return " ".join(result)
21
22 def chunk(self, n: int) -> List[str]:
23 words = []
24 if n >= 100:
25 words += [self.BELOW_20[n // 100], "Hundred"]
26 n %= 100
27 if n >= 20:
28 words.append(self.TENS[n // 10])
29 n %= 10
30 if n > 0:
31 words.append(self.BELOW_20[n])
32 return words1class Solution {
2 private static final String[] BELOW_20 = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
3 private static final String[] TENS = {"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
4 private static final String[] SCALES = {"", "Thousand", "Million", "Billion"};
5
6 public String numberToWords(int num) {
7 if (num == 0) {
8 return "Zero";
9 }
10 List<String> result = new ArrayList<>();
11 int i = 0;
12 while (num > 0) {
13 int group = num % 1000;
14 if (group > 0) {
15 List<String> words = chunk(group);
16 if (!SCALES[i].isEmpty()) {
17 words.add(SCALES[i]);
18 }
19 result.addAll(0, words);
20 }
21 num /= 1000;
22 i++;
23 }
24 return String.join(" ", result);
25 }
26
27 private List<String> chunk(int n) {
28 List<String> words = new ArrayList<>();
29 if (n >= 100) {
30 words.add(BELOW_20[n / 100]);
31 words.add("Hundred");
32 n %= 100;
33 }
34 if (n >= 20) {
35 words.add(TENS[n / 10]);
36 n %= 10;
37 }
38 if (n > 0) {
39 words.add(BELOW_20[n]);
40 }
41 return words;
42 }
43}1class Solution {
2 const vector<string> below20 = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
3 const vector<string> tens = {"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
4 const vector<string> scales = {"", "Thousand", "Million", "Billion"};
5
6public:
7 string numberToWords(int num) {
8 if (num == 0) {
9 return "Zero";
10 }
11 vector<string> result;
12 int i = 0;
13 while (num > 0) {
14 int group = num % 1000;
15 if (group > 0) {
16 vector<string> words = chunk(group);
17 if (!scales[i].empty()) {
18 words.push_back(scales[i]);
19 }
20 result.insert(result.begin(), words.begin(), words.end());
21 }
22 num /= 1000;
23 i++;
24 }
25 string out;
26 for (size_t k = 0; k < result.size(); k++) out += (k ? " " : "") + result[k];
27 return out;
28 }
29
30private:
31 vector<string> chunk(int n) {
32 vector<string> words;
33 if (n >= 100) {
34 words.push_back(below20[n / 100]);
35 words.push_back("Hundred");
36 n %= 100;
37 }
38 if (n >= 20) {
39 words.push_back(tens[n / 10]);
40 n %= 10;
41 }
42 if (n > 0) {
43 words.push_back(below20[n]);
44 }
45 return words;
46 }
47};Time and space complexity
O(1)
A 32-bit integer has at most four groups of three digits, each converted with constant work.
O(1)
The word tables are fixed and the output has a bounded number of words.
Other approaches
Recursion on thresholds (time O(1), space O(1))
Write words(n): below 20 use the table, below 100 use tens plus words(n % 10), below 1000 use words(n / 100) Hundred words(n % 100), and for larger n divide by the biggest scale that fits. Trim extra spaces at the end. Short, but easy to leave double spaces.
Common mistakes
- Emitting a scale word for a zero group.
1000010is"One Million Ten", not"One Million Thousand Ten": skip groups equal to 0 entirely. - Splitting teens into tens and ones. 10 to 19 have their own words, so only use the tens table when the remainder is 20 or more.
- Producing double or trailing spaces when parts are empty. Collect words in a list and join once.
- Forgetting
num = 0, the only input where the loop never runs.
Frequently asked questions
Why process groups from the right?
num % 1000 and num / 1000 naturally give the rightmost group first, and the index of the loop gives the scale. Prepending each group's words keeps the sentence in spoken order.
Why does zero need a special case?
Zero is the only number with no non-zero group, so the loop would produce an empty string. Every other zero, such as in 105 or 1000, is simply silent.
Does the answer use "and" or hyphens?
No. The expected format is plain capitalised words separated by single spaces, so 105 is "One Hundred Five" and 21 is "Twenty One".