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
0directly 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
Understand the input range and formatting rules
We are given an integer
numbetween0and2,147,483,647(2^31 - 1, about 2.14 billion) and asked to return its American English name:0returns"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"(8012is"Eight Thousand Twelve", not"Eight Thousand and Twelve"). - Use the scale words
"Thousand","Million", and"Billion". Becausenum <= 2,147,483,647,"Billion"is the largest scale we ever need.
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
1to999, followed by its scale word ("Billion","Million","Thousand", or nothing for the last chunk). 2. Whenever a 3-digit chunk is000, 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)for0 <= chunk < 1000, then call it from"Billion"down to the final< 1000remainder.Build the helper for a single 3-digit chunk (0 to 999)
Inside a single 3-digit chunk, English numbers have three zones:
- Hundreds (
100..999): the digitchunk // 100(1..9) followed by"Hundred", leaving remainderchunk % 100. - Regular tens (
20..99): a decade word ("Twenty"through"Ninety", watch the spelling of"Forty") fromchunk // 10, leaving remainderchunk % 10. - Ones and teens (
1..19):1through19each have a unique single word ("One".."Nine","Ten","Eleven".."Nineteen"). Keeping all 19 in oneUNDER_TWENTYlist and checkingchunk >= 20beforechunk > 0ensures16becomes["Sixteen"]instead of["Ten", "Six"].
Returning a
List[str](and[]for0) 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- Hundreds (
Walk the scales from Billion down to the ones chunk
Now handle
num == 0right at the top. For anynum > 0, step throughSCALESfrom1_000_000_000("Billion") down to1_000("Thousand"):- Whenever
num >= scale_value, the chunknum // scale_valueis between1and999. Append its words, appendscale_name, and keep the remaindernum % scale_value. - Whenever
num < scale_value, that scale's 3-digit chunk is0, so theifskips both the chunk words andscale_name. - After the loop finishes,
numholds the final< 1000chunk; extendwordswith_spell_chunk_under_1000(num)(which adds nothing ifnum == 0, as in1000 -> "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)- Whenever
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"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 isO(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 alsoO(1)for 32-bit integers. The lookup listsUNDER_TWENTY,TENS, andSCALEShave fixed constant sizes, and thewordslist holds at most 19 strings before producing the output string.
Edge cases
- Input
0: handled up front and returns"Zero"; for everynum > 0, a zero digit or000chunk produces no words at all. - Irregular teens (
10to19):10, 11, 12, ..., 19map directly to single words inUNDER_TWENTYbecausechunk >= 20is false. - Exact multiples of 10 or 100:
40produces"Forty"and500produces"Five Hundred"with no trailing"Zero". - Skipped middle scale groups (
000):1,000,000,001skips bothMillionandThousand, returning"One Billion One". - Exact scale boundaries:
1,000,1,000,000, and1,000,000,000leave a final remainder of0, 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 is2(< 1000), so_spell_chunk_under_1000handles it without needing a"Trillion"entry.
Common mistakes
- Concatenating strings manually (
ans += " " + w): creates leading spaces, trailing spaces on round numbers like1000, or double spaces when a chunk is0. Collecting words in alistand calling" ".join(words)once eliminates spacing bugs completely. - Emitting the scale name when its 3-digit chunk is
0: turns1,000,010into"One Million Thousand Ten". Only appendscale_namewhennum >= scale_value. - Splitting
10..19into tens + ones: checkingchunk >= 10for the tens table turns15into"Ten Five"instead of"Fifteen". Always guard the tens table withchunk >= 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 dividesn, recursively spelln // unit, append the unit name, and recursively spelln % unitif nonzero (tests.pyuses this compact idea as its cross-check oracle). The iterativeSCALES+_spell_chunk_under_1000design is just as short and avoids recursion while mirroring how humans read comma-separated groups. - Right-to-left
num % 1000loop: repeatedly peel off the lowest three digits withnum % 1000andnum //= 1000while advancing a scale index0, 1, 2, 3. It avoids hard-coding1_000_000_000first, 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-bitint, cast to 64-bitlong longbefore negating so-2,147,483,648does 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")toSCALES. - How would you support British English formatting where the word and is required? British style inserts
"and"before a nonzero< 100part whenever higher units precede it (for example,"Three Hundred and Eight"and"Eight Thousand and Twelve"). You can pass aninclude_and: boolflag that inserts"and"inside_spell_chunk_under_1000after"Hundred"whenchunk % 100 > 0, and also before the final< 100remainder whenwordsis 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_totalfor the current< 1000group andgrand_totalfor completed scale groups. Number words ("One".."Ninety") add tochunk_total,"Hundred"multiplieschunk_totalby100, and scale words ("Thousand","Million","Billion") addchunk_total * scale_valueintogrand_totaland resetchunk_total = 0, returninggrand_total + chunk_totalat the end.
Follow-up questions
- How would you extend the function to negative integers and 64-bit numbers?
- How would you support British English formatting where the word and is required?
- How would you write the inverse function that parses English words back into an integer?
Similar questions
- Stakeholder Alignment, AI Workflows, and Plain-Language Communication
- Workforce Time-Tracking and Payroll Backend Design
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance