Integer to English Words
Spell out a non-negative integer num as English words, exactly as you'd say it out loud. Your solution needs to handle everything from 0 up through 2^31 - 1, following the usual English number-naming pattern of breaking the value into Billion, Million, and Thousand groupings, each of which is itself built from Hundreds, Tens, and Ones.
Input Format
Implement numberToWords(num). Inputs below show JavaScript function arguments; there is no stdin parsing.
Output Format
Return the result described in the statement.
Sample Input and Output
Example 1 ยท Run Sample
Input
num = 123 Output
"One Hundred Twenty Three" Example 2
Input
num = 0 Output
"Zero" Constraints
- 0 <= num <= 2^31 - 1
Test Cases (2)
Case 1
Args: [123]
Expected: "One Hundred Twenty Three"
Case 2
Args: [0]
Expected: "Zero"
Topics
Chunk by Thousands
function numberToWords(num) {
if (num === 0) return "Zero";
const ones = ['','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 '';
if (n < 20) return ones[n] + ' ';
if (n < 100) return tens[Math.floor(n/10)] + ' ' + helper(n%10);
return ones[Math.floor(n/100)] + ' Hundred ' + helper(n%100);
}
let result = '', i = 0;
while (num > 0) {
if (num % 1000 !== 0) result = helper(num % 1000) + thousands[i] + ' ' + result;
num = Math.floor(num / 1000); i++;
}
return result.trim();
}Time: O(1) | Space: O(1)
Saved in this browser only. Private to you.