Integer to English Words
HardMathStringRecursion
Solution
export function numberToWords(num: number): string {
return num === 0 ? 'Zero' : helper(num).trim();
}
const ONES = [
'',
'One',
'Two',
'Three',
'Four',
'Five',
'Six',
'Seven',
'Eight',
'Nine',
'Ten',
'Eleven',
'Twelve',
'Thirteen',
'Fourteen',
'Fifteen',
'Sixteen',
'Seventeen',
'Eighteen',
'Nineteen',
];
const TENS = [
'',
'Ten',
'Twenty',
'Thirty',
'Forty',
'Fifty',
'Sixty',
'Seventy',
'Eighty',
'Ninety',
];
const THOUSANDS = ['', 'Thousand', 'Million', 'Billion'];
function helper(num: number): string {
if (num < 20) {
return ONES[num];
}
if (num < 100) {
return `${TENS[Math.floor(num / 10)]} ${helper(num % 10)}`.trim();
}
if (num < 1000) {
return `${helper(Math.floor(num / 100))} Hundred ${helper(num % 100)}`.trim();
}
const i = Math.floor(Math.log10(num) / 3);
const unit = 10 ** (3 * i);
return `${helper(Math.floor(num / unit))} ${THOUSANDS[i]} ${helper(num % unit)}`.trim();
}
Complexity
- Time:
O(log10(N))
- Space:
O(log10(N))