scale decomposition
Divide the number by 1 billion, 1 million, 1 thousand, and 1 in descending order. Each quotient becomes a chunk. Each non-zero chunk gets converted and its scale word is appended.
When a check-printing system writes "One Million Two Hundred Thirty Four
Thousand Five Hundred Sixty Seven" beneath a dollar amount, it decomposes
the number into three-digit groups — billions, millions, thousands, ones —
converts each chunk independently using a small vocabulary of ones, teens,
tens, and "Hundred," then attaches the scale word. Zero-valued groups are
silently skipped. O(1) time. O(1) space.
The algorithm works in three nested levels: scale decomposition, below-thousand conversion, and vocabulary lookup.
Divide the number by 1 billion, 1 million, 1 thousand, and 1 in descending order. Each quotient becomes a chunk. Each non-zero chunk gets converted and its scale word is appended.
Each chunk (0–999) follows one rule: if ≥ 100, speak the hundreds digit + "Hundred"; if ≥ 20, speak the tens word; if the remainder is 1–19, speak the ones or teen word directly.
When a chunk is zero, its entire group — including the scale word — is omitted. This is why 1,000,010 becomes "One Million Ten" with no "Thousand" in between.
A loop over four scale groups with a helper for below-thousand conversion.
If the number is 0, return "Zero" immediately. Zero has no scale decomposition.
For each scale (Billion → Million → Thousand → ones): divide the remaining number by the scale value. The quotient is the chunk; the remainder carries forward.
For non-zero chunks, convert the value (0–999) to words: hundreds place, tens place, then ones or teens. Attach the scale word if the group is above ones.
Concatenate the word fragments from all non-zero groups with single spaces.
Most pitfalls involve groups that produce no words or values that bypass the normal tens + ones pattern.
1,000,010 has a zero thousands chunk. Without the skip check, the output would incorrectly include "Thousand" with no preceding words.
Values 10 through 19 use dedicated words — "Eleven", "Twelve" —
instead of combining a tens word with a ones word. The range check
n < 20 must precede the tens lookup.
100 is "One Hundred", not "One Hundred Zero". 1,000 is "One Thousand", not "One Thousand Zero Hundred". Every sub-conversion must guard against appending words for zero sub-values.