Convert Integer to American English Words

Easy · Coding & Algorithms · Software Engineer · Onsite

Problem Statement

Write a function spell_out_integer(num: int) -> str that converts a non-negative integer num into its spoken American English phrase.

Follow these formatting conventions:

  • Map 0 directly to "Zero" (the word "Zero" never appears anywhere in the output for positive integers).
  • Group large magnitudes using the scale labels "Thousand" (1,000), "Million" (1,000,000), and "Billion" (1,000,000,000). Skip any three-digit group whose value is zero along with its scale label.
  • Capitalize the initial letter of every word ("Three Hundred Forty Eight").
  • Separate consecutive words with a single ASCII space (" "), without hyphens, commas, leading spaces, or trailing spaces.
  • Never insert the conjunction "and" between hundreds and tens/ones or across scale boundaries.

Examples

Example 1

Input: num = 4 Output: "Four" Explanation: Single-digit positive integers map directly to their base English word.

Example 2

Input: num = 16 Output: "Sixteen" Explanation: Integers from 10 through 19 use dedicated single-word teen names rather than separate tens and ones words.

Example 3

Input: num = 348 Output: "Three Hundred Forty Eight" Explanation: 3 hundreds followed by 40 ("Forty", spelled without a 'u') and 8, joined by single spaces with no "and" or hyphen.

Example 4

Input: num = 8012 Output: "Eight Thousand Twelve" Explanation: The thousands group is 8 ("Eight Thousand"), the hundreds digit in 012 is zero and omitted, and the remaining 12 spells "Twelve".

Example 5

Input: num = 4050720 Output: "Four Million Fifty Thousand Seven Hundred Twenty" Explanation: Splitting at the commas gives 4 million, 50 thousand, and 720, with trailing zero ones digits silent in both 50 and 720.

Example 6

Input: num = 1900042615 Output: "One Billion Nine Hundred Million Forty Two Thousand Six Hundred Fifteen" Explanation: Evaluating the four comma groups from largest to smallest yields 1 billion, 900 million, 42 thousand, and 615.

Constraints

  • 0 <= num <= 2,147,483,647 (2^31 - 1).

Step-by-step walkthrough

  1. Understand the input range and formatting rules

    We are given an integer num between 0 and 2,147,483,647 (2^31 - 1, about 2.14 billion) and asked to return its American English name:

    • 0 returns "Zero", and no other number ever contains the word "Zero".
    • Every word is capitalized ("Three Hundred Forty Eight"), joined by single spaces with no leading or trailing spaces.
    • Never insert "and" (8012 is "Eight Thousand Twelve", not "Eight Thousand and Twelve").
    • Use the scale words "Thousand", "Million", and "Billion". Because num <= 2,147,483,647, "Billion" is the largest scale we ever need.
  2. Key idea: split at the commas into 3-digit chunks

    Look at how commas divide a large integer when we write it out:

      1 , 900 , 042 , 615
      |    |     |     |
      v    v     v     v
      1   900    42   615    <-- each chunk is a small integer in 0..999!
      |    |     |     |
    Billion Million Thousand (no scale word)
    
      4 , 000 , 016
      |    |     |
      4   000   016
      |    |     |
    Million (skip!) Sixteen  --> "Four Million Sixteen" (all-zero chunk drops its scale word too!)
    

    Notice two things in that diagram: 1. Every 3-digit chunk is spelled by the exact same rules as a standalone number from 1 to 999, followed by its scale word ("Billion", "Million", "Thousand", or nothing for the last chunk). 2. Whenever a 3-digit chunk is 000, it stays completely silent—not even its scale word is spoken.

    That splits our job cleanly in two: write one helper _spell_chunk_under_1000(chunk) for 0 <= chunk < 1000, then call it from "Billion" down to the final < 1000 remainder.

  3. Build the helper for a single 3-digit chunk (0 to 999)

    Inside a single 3-digit chunk, English numbers have three zones:

    1. Hundreds (100..999): the digit chunk // 100 (1..9) followed by "Hundred", leaving remainder chunk % 100.
    2. Regular tens (20..99): a decade word ("Twenty" through "Ninety", watch the spelling of "Forty") from chunk // 10, leaving remainder chunk % 10.
    3. Ones and teens (1..19): 1 through 19 each have a unique single word ("One" .. "Nine", "Ten", "Eleven" .. "Nineteen"). Keeping all 19 in one UNDER_TWENTY list and checking chunk >= 20 before chunk > 0 ensures 16 becomes ["Sixteen"] instead of ["Ten", "Six"].

    Returning a List[str] (and [] for 0) instead of concatenating strings means we never have to clean up extra spaces:

    chunk = 348  -->  >=100: ["Three", "Hundred"], rem 48
                 -->  >=20:  + ["Forty"],          rem 8
                 -->  >0:    + ["Eight"]           --> ["Three", "Hundred", "Forty", "Eight"]
    
    chunk = 16   -->  <100, <20, >0                --> ["Sixteen"]
    chunk = 40   -->  <100, >=20: ["Forty"], rem 0 --> ["Forty"]
    chunk = 0    -->  all checks False             --> []
    
    # UNDER_TWENTY[n] holds the unique English word for 1 <= n <= 19; index 0 is unused ("").
    # Keeping 1..19 in one table handles irregular teen words (Eleven..Nineteen) without extra branches.
    UNDER_TWENTY = [
        "", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine",
        "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen",
        "Seventeen", "Eighteen", "Nineteen",
    ]
    
    # TENS[d] holds the decade word for d * 10 when 2 <= d <= 9 (note: "Forty" has no 'u').
    TENS = [
        "", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety",
    ]
    
    
    def _spell_chunk_under_1000(chunk: int) -> List[str]:
        """Spell 0 <= chunk < 1000 as a list of words; return [] when chunk == 0."""
        chunk_words: List[str] = []
    
        # Phase 1: peel off the hundreds digit (100..999).
        if chunk >= 100:
            hundreds_digit = chunk // 100
            chunk_words.append(UNDER_TWENTY[hundreds_digit])
            chunk_words.append("Hundred")
            chunk = chunk % 100
    
        # Phase 2: peel off regular tens (20..99); checking >= 20 leaves 10..19 intact for Phase 3.
        if chunk >= 20:
            tens_digit = chunk // 10
            chunk_words.append(TENS[tens_digit])
            chunk = chunk % 10
    
        # Phase 3: handle remaining 1..19 (or do nothing when chunk == 0 so 'Zero' never leaks in).
        if chunk > 0:
            chunk_words.append(UNDER_TWENTY[chunk])
    
        return chunk_words
    
  4. Walk the scales from Billion down to the ones chunk

    Now handle num == 0 right at the top. For any num > 0, step through SCALES from 1_000_000_000 ("Billion") down to 1_000 ("Thousand"):

    • Whenever num >= scale_value, the chunk num // scale_value is between 1 and 999. Append its words, append scale_name, and keep the remainder num % scale_value.
    • Whenever num < scale_value, that scale's 3-digit chunk is 0, so the if skips both the chunk words and scale_name.
    • After the loop finishes, num holds the final < 1000 chunk; extend words with _spell_chunk_under_1000(num) (which adds nothing if num == 0, as in 1000 -> "One Thousand") and join with " ".
    # SCALES lists (scale_value, scale_name) from largest to smallest so chunks emit in reading order.
    SCALES = [
        (1_000_000_000, "Billion"),
        (1_000_000, "Million"),
        (1_000, "Thousand"),
    ]
    
    
    def spell_out_integer(num: int) -> str:
        # 0 is the only input where the word "Zero" appears anywhere in the output.
        if num == 0:
            return "Zero"
    
        # words: flat list of capitalized English words, e.g. ["Eight", "Thousand", "Twelve"]
        words: List[str] = []
    
        # Walk Billion -> Million -> Thousand; skip any scale whose 3-digit chunk is 0.
        for scale_value, scale_name in SCALES:
            if num >= scale_value:
                chunk = num // scale_value
                words.extend(_spell_chunk_under_1000(chunk))
                words.append(scale_name)
                num = num % scale_value
    
        # Append the final ones chunk (0..999), which carries no scale word.
        words.extend(_spell_chunk_under_1000(num))
    
        # Joining once at the end guarantees single spaces with no leading or trailing whitespace.
        return " ".join(words)
    
  5. Trace tricky inputs step by step

    Let's verify both a sparse thousands input (8012, Example 4) and a billion-scale input (1,900,042,615, Example 6):

    Trace 1: num = 8012
      1_000_000_000 (Billion):  8012 < 1_000_000_000 -> skip
      1_000_000     (Million):  8012 < 1_000_000     -> skip
      1_000         (Thousand): chunk = 8  -> ["Eight"] + ["Thousand"], num becomes 12
      Final ones chunk:         chunk = 12 -> ["Twelve"]
      " ".join(words) -> "Eight Thousand Twelve"
    
    Trace 2: num = 1,900,042,615
      1_000_000_000 (Billion):  chunk = 1   -> ["One", "Billion"], rem = 900,042,615
      1_000_000     (Million):  chunk = 900 -> ["Nine", "Hundred", "Million"], rem = 42,615
      1_000         (Thousand): chunk = 42  -> ["Forty", "Two", "Thousand"], rem = 615
      Final ones chunk:         chunk = 615 -> ["Six", "Hundred", "Fifteen"]
      " ".join(words) ->
        "One Billion Nine Hundred Million Forty Two Thousand Six Hundred Fifteen"
    
  6. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    # UNDER_TWENTY[n] holds the unique English word for 1 <= n <= 19; index 0 is unused ("").
    # Keeping 1..19 in one table handles irregular teen words (Eleven..Nineteen) without extra branches.
    UNDER_TWENTY = [
        "", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine",
        "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen",
        "Seventeen", "Eighteen", "Nineteen",
    ]
    
    # TENS[d] holds the decade word for d * 10 when 2 <= d <= 9 (note: "Forty" has no 'u').
    TENS = [
        "", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety",
    ]
    
    # SCALES lists (scale_value, scale_name) from largest to smallest so chunks emit in reading order.
    SCALES = [
        (1_000_000_000, "Billion"),
        (1_000_000, "Million"),
        (1_000, "Thousand"),
    ]
    
    
    def _spell_chunk_under_1000(chunk: int) -> List[str]:
        """Spell 0 <= chunk < 1000 as a list of words; return [] when chunk == 0."""
        chunk_words: List[str] = []
    
        # Phase 1: peel off the hundreds digit (100..999).
        if chunk >= 100:
            hundreds_digit = chunk // 100
            chunk_words.append(UNDER_TWENTY[hundreds_digit])
            chunk_words.append("Hundred")
            chunk = chunk % 100
    
        # Phase 2: peel off regular tens (20..99); checking >= 20 leaves 10..19 intact for Phase 3.
        if chunk >= 20:
            tens_digit = chunk // 10
            chunk_words.append(TENS[tens_digit])
            chunk = chunk % 10
    
        # Phase 3: handle remaining 1..19 (or do nothing when chunk == 0 so 'Zero' never leaks in).
        if chunk > 0:
            chunk_words.append(UNDER_TWENTY[chunk])
    
        return chunk_words
    
    
    def spell_out_integer(num: int) -> str:
        # 0 is the only input where the word "Zero" appears anywhere in the output.
        if num == 0:
            return "Zero"
    
        # words: flat list of capitalized English words, e.g. ["Eight", "Thousand", "Twelve"]
        words: List[str] = []
    
        # Walk Billion -> Million -> Thousand; skip any scale whose 3-digit chunk is 0.
        for scale_value, scale_name in SCALES:
            if num >= scale_value:
                chunk = num // scale_value
                words.extend(_spell_chunk_under_1000(chunk))
                words.append(scale_name)
                num = num % scale_value
    
        # Append the final ones chunk (0..999), which carries no scale word.
        words.extend(_spell_chunk_under_1000(num))
    
        # Joining once at the end guarantees single spaces with no leading or trailing whitespace.
        return " ".join(words)
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of how commas break up a large dollar amount on a paper check: 4,050,720 is really just three small numbers—4, 50, and 720—followed by the group labels "Million", "Thousand", and nothing at the end. Once you know how to spell a single 3-digit chunk from 1 to 999, spelling a billion-scale number is just repeating that exact same helper at each comma from left to right.

A naive digit-by-digit approach that glues strings together with += " " + word quickly tangles itself into bugs. English treats 10 through 19 as single irregular words (16 is "Sixteen", not "Ten Six"), drops zero digits completely (40 is "Forty", not "Forty Zero"), drops entire all-zero comma groups (4,000,016 has no "Thousand" at all), and easily leaves leading, trailing, or double spaces when middle digits are zero.

Instead, we store the irregular words 1..19 in one lookup table (a fixed array indexed directly by number so UNDER_TWENTY[16] returns "Sixteen" in one step), peel off hundreds, 20..99 tens, and 1..19 using integer division // (quotient without remainder) and modulo % (the remainder left over), and collect every spoken word into a Python list before calling " ".join(words) once at the very end.

Walk through a tiny example with num = 3,008,016: 1. At "Million" (1,000,000), 3,008,016 // 1,000,000 = 3 appends ["Three", "Million"], leaving remainder 8,016. 2. At "Thousand" (1,000), 8,016 // 1,000 = 8 appends ["Eight", "Thousand"], leaving remainder 16. 3. The final < 1000 chunk 16 skips >= 100 and >= 20, hits UNDER_TWENTY[16], and appends ["Sixteen"]. 4. " ".join(words) produces "Three Million Eight Thousand Sixteen" with clean single spaces.

Complexity

Let d be the number of base-10 digits in num (for num <= 2,147,483,647, d <= 10).

  • Time: O(d), which is O(1) constant time for 32-bit integers. We inspect at most four 3-digit groups (Billion, Million, Thousand, and ones), doing at most three constant-time arithmetic checks and table lookups per group (at most 19 words total) before joining them once.
  • Space: O(d), which is also O(1) for 32-bit integers. The lookup lists UNDER_TWENTY, TENS, and SCALES have fixed constant sizes, and the words list holds at most 19 strings before producing the output string.

Edge cases

  • Input 0: handled up front and returns "Zero"; for every num > 0, a zero digit or 000 chunk produces no words at all.
  • Irregular teens (10 to 19): 10, 11, 12, ..., 19 map directly to single words in UNDER_TWENTY because chunk >= 20 is false.
  • Exact multiples of 10 or 100: 40 produces "Forty" and 500 produces "Five Hundred" with no trailing "Zero".
  • Skipped middle scale groups (000): 1,000,000,001 skips both Million and Thousand, returning "One Billion One".
  • Exact scale boundaries: 1,000, 1,000,000, and 1,000,000,000 leave a final remainder of 0, so _spell_chunk_under_1000(0) returns [] and nothing follows the scale word.
  • Maximum 32-bit signed integer (2,147,483,647): the "Billion" chunk is 2 (< 1000), so _spell_chunk_under_1000 handles it without needing a "Trillion" entry.

Common mistakes

  • Concatenating strings manually (ans += " " + w): creates leading spaces, trailing spaces on round numbers like 1000, or double spaces when a chunk is 0. Collecting words in a list and calling " ".join(words) once eliminates spacing bugs completely.
  • Emitting the scale name when its 3-digit chunk is 0: turns 1,000,010 into "One Million Thousand Ten". Only append scale_name when num >= scale_value.
  • Splitting 10..19 into tens + ones: checking chunk >= 10 for the tens table turns 15 into "Ten Five" instead of "Fifteen". Always guard the tens table with chunk >= 20.
  • Spelling typos in lookup tables: writing "Fourty" instead of "Forty", "Eightty" instead of "Eighty", or "Ninty" instead of "Ninety" fails exact string assertions immediately.
  • Inserting "and" out of habit: writing "Three Hundred and Forty Eight" violates the American English requirement in the prompt.

Alternative approaches

  • Recursive decomposition by largest scale: find the largest unit in (10^9, 10^6, 10^3, 100) that divides n, recursively spell n // unit, append the unit name, and recursively spell n % unit if nonzero (tests.py uses this compact idea as its cross-check oracle). The iterative SCALES + _spell_chunk_under_1000 design is just as short and avoids recursion while mirroring how humans read comma-separated groups.
  • Right-to-left num % 1000 loop: repeatedly peel off the lowest three digits with num % 1000 and num //= 1000 while advancing a scale index 0, 1, 2, 3. It avoids hard-coding 1_000_000_000 first, though you have to collect chunk phrases in reverse and reverse them before joining.

Follow-up questions

  • How would you extend the function to negative integers and 64-bit numbers? If num < 0, prepend "Negative" to the word list and run the exact same logic on -num (in C++ or Java with fixed-width 32-bit int, cast to 64-bit long long before negating so -2,147,483,648 does not overflow). To cover 64-bit integers (up to ~9.22 * 10^18), simply prepend (10**18, "Quintillion"), (10**15, "Quadrillion"), and (10**12, "Trillion") to SCALES.
  • How would you support British English formatting where the word and is required? British style inserts "and" before a nonzero < 100 part whenever higher units precede it (for example, "Three Hundred and Eight" and "Eight Thousand and Twelve"). You can pass an include_and: bool flag that inserts "and" inside _spell_chunk_under_1000 after "Hundred" when chunk % 100 > 0, and also before the final < 100 remainder when words is already non-empty.
  • How would you write the inverse function that parses English words back into an integer? Maintain two running integers as you scan words left to right: chunk_total for the current < 1000 group and grand_total for completed scale groups. Number words ("One".."Ninety") add to chunk_total, "Hundred" multiplies chunk_total by 100, and scale words ("Thousand", "Million", "Billion") add chunk_total * scale_value into grand_total and reset chunk_total = 0, returning grand_total + chunk_total at the end.

Follow-up questions

Similar questions

More Carvana interview questions

All 3 Carvana questions →