08. Integer to English Words
Convert a non-negative integer num to its English words representation.
How It Works & Algorithmic Design
Solves using Chunking by Thousands with Static Word Arrays:
- Static Lookup Arrays: Define arrays for units
["", "One", ...], teens["Ten", "Eleven", ...], tens["", "", "Twenty", ...], and thousands["", "Thousand", "Million", "Billion"]. - Three-Digit Helper
helper(n):- If $n < 20$, lookup units/teens.
- If $n < 100$, return
tens[n/10] + helper(n%10). - If $n \ge 100$, return
units[n/100] + " Hundred " + helper(n%100).
- Loop Thousands: Process
numin 3-digit chunks, appending thousand group names.
Why This Approach Works Best
Recursively converts 3-digit groups in $O(1)$ constant time.
Example Walkthrough
Input:
num = 1234567Target integer.
Chunks:
1 (Million) + 234 (Thousand) + 5673-digit groups.
Output:
"One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"Converted text.
Answer: Integer to English Words implementation
function numberToWords(num) {
if (num === 0) return 'Zero';
const LESS_THAN_20 = ['', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen'];
const TENS = ['', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety'];
const THOUSANDS = ['', 'Thousand', 'Million', 'Billion'];
function helper(n) {
if (n === 0) return '';
else if (n < 20) return LESS_THAN_20[n] + ' ';
else if (n < 100) return TENS[Math.floor(n / 10)] + ' ' + helper(n % 10);
else return LESS_THAN_20[Math.floor(n / 100)] + ' Hundred ' + helper(n % 100);
}
let res = '', i = 0;
while (num > 0) {
if (num % 1000 !== 0) {
res = helper(num % 1000) + THOUSANDS[i] + ' ' + res;
}
num = Math.floor(num / 1000);
i++;
}
return res.trim().replace(/\s+/g, ' ');
}💡 Parse number in groups of 3 digits appending Thousand, Million, and Billion suffix scale tags.
Key Takeaways
- Chunks integers into 3-digit groups (thousands scale).
- Helper function handles standard sub-1000 numbers recursively.
- Executes in $O(1)$ bounded time.