AlgoInsight

DSA problem

Integer to English Words

HardRecursionPattern: Recursiontop600MicrosoftAmazonFacebookAppleGoogleLinkedIn

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

Example 1
Input: num = 123
Output: "One Hundred Twenty Three"
Explanation: A single three-digit group. Hundreds: "One Hundred"; tens-and-ones: "Twenty Three".
Example 2
Input: num = 12345
Output: "Twelve Thousand Three Hundred Forty Five"
Explanation: Top group is 12 ("Twelve") with scale "Thousand"; bottom group is 345 ("Three Hundred Forty Five").
Example 3
Input: num = 1234567
Output: "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"
Explanation: Three groups: 1 ("One") with scale "Million", 234 ("Two Hundred Thirty Four") with scale "Thousand", and 567 ("Five Hundred Sixty Seven") with no scale.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

recursionmathstring

Browse all DSA problems