DSA problem
Integer to English Words
Convert a non-negative integer num to its English words representation. The number can be as large as 2^31 - 1, i.e. up to roughly 2.1 billion, so your solution must handle Billion, Million, and Thousand groupings.
The natural way to read out a large number aloud is to split it into three-digit groups from the right and label them with their appropriate scale word: the bottom three digits have no suffix, the next three are "Thousand", then "Million", then "Billion". Each three-digit group is itself read using the same rules: hundreds, tens, and ones.
The optimal recursive design therefore has two levels. A helper converts any value in the range 0..999 to words by recursing into the hundreds, tens, and units. A top-level routine pulls off three-digit groups from the integer, calls the helper on each, and appends the matching scale word when the group is non-zero. The string "Zero" is the single special case at the top.
Edge cases to handle carefully: leading or trailing whitespace must be trimmed; groups that evaluate to zero must be skipped (otherwise you would emit "Zero Million"); and the tens range 10..19 is irregular ("Eleven", "Twelve", …, "Nineteen") and must be handled as a special table rather than via the "Twenty One" pattern. The recursion runs in O(log10 n) time and uses O(log10 n) recursion depth.
Examples
num = 123"One Hundred Twenty Three"num = 12345"Twelve Thousand Three Hundred Forty Five"num = 1234567"One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"Constraints
- 0 <= num <= 2^31 - 1
3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.