You are given a whole number num that is 0 or more. Return how it is said in English, as words with a capital first letter, separated by single spaces.
Use American style: no "and", no commas, no hyphens. For example, 1,234 is "One Thousand Two Hundred Thirty Four".
Example 1
Input: num = 507 Output: "Five Hundred Seven" Why: the tens digit is 0, so it says nothing
2 more examples and the constraints
Example 2
Input: num = 6000080 Output: "Six Million Eighty" Why: the thousands group is all zeros
Example 3
Input: num = 0 Output: "Zero" Why: the one number that is not built from parts
Constraints
- 0 ≤ num ≤ 2,147,483,647
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Recursion on the largest unitO(log num)
- Groups of three digitsO(log num)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for num = 2,147,483,647 | Verdict |
|---|---|---|---|
| Recursion on the largest unit | O(log num) | Passes; reads like the rule | |
| Groups of three digits | O(log num) | Best; one helper, no recursion |
num = the input; log num is about its number of digits.
Edge cases to test
- Zero. 0 is "Zero", and it is the only time that word appears.
- A group of zeros. 6,000,080 skips the thousands group entirely: "Six Million Eighty".
- Teens. 13 and 2,004,019 need the 10-to-19 words, not "Ten Three".
- Exact tens and hundreds. 20, 100 and 110 must not end in a stray space or an empty word.
- The largest input. 2,147,483,647 uses all four units.
Common mistakes
- Printing a unit for an all-zero group, as in "One Million Thousand".
- Leaving double or trailing spaces when a part is empty, as in "Twenty ".
- Splitting 10 to 19 into a tens word and a ones word instead of using the teen words.
How to talk through it
- 1Clarify. What is the output for 0? Any "and", commas or hyphens? Is num ever negative?
- 2Find the repeat. Every three digits are said the same way; only the unit after them changes.
- 3Write the helper. Words for 1 to 999: hundreds, then a teen word or tens plus ones.
- 4Loop over groups. Peel off num % 1000, skip zeros, add the unit, and reverse at the end.
- 5Test out loud. Run 0, 13, 100, 6,000,080 and 2,147,483,647.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?