Integer to English Words
Hard · Math · Math · String · Recursion
Problem
Given a non-negative integer num, return its spelling in English words.
Use the short-scale group names Thousand, Million and Billion. Capitalize every word, separate words with single spaces, and use no "And" and no hyphens (write "Forty Two"). Groups that are zero are left out entirely. The number 0 is written "Zero".
Examples
Input: num = 405 Output: "Four Hundred Five"
No "And", and nothing for the zero in the tens place.
Input: num = 7000019 Output: "Seven Million Nineteen"
The thousands group is 000, so it is left out.
Input: num = 1234567891 Output: "One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One"
Each three-digit group is spelled and followed by its scale word.
Constraints
- 0 <= num <= 2^31 - 1
Approaches
- Baseline: recurse on the largest scale — time O(1), with string rebuilding at each level, space O(1) (bounded recursion depth)
Follow-up
How would you go the other way, from the words back to the number? (One of the use cases asks exactly that.) And what changes for a language whose numbers are grouped differently, such as lakh and crore?
Related problems
Start free on Cariara · Coding problems · System design studio