← Questions
Integer to English words, built up by range
0
I was asked this
No reports yet. Sign in to say where you were asked it.
Write a function that spells out an integer in English words. The interviewer adds the ranges in parts, and later parts should reuse earlier ones, so design for extension from the start.
-
Digits.
digit_to_words(n)for0 <= n <= 9. Raise an error for anything else. -
Two digits. Extend to
0 <= n <= 99. Watch the irregular words for 10-19. -
Three digits. Extend to
0 <= n <= 999. -
Full range.
number_to_words(num)for any 32-bit signed integer, using the scale words Thousand, Million and Billion. - Negatives. A negative number starts with the word "Negative".
Output format
- Words are capitalized and separated by single spaces, with no leading or trailing space.
- No "and", no hyphens, and no commas ("Sixty Two", not "sixty-two").
- Zero parts are left out: 40 is "Forty", and 3,000,020 is "Three Million Twenty". Only the input 0 itself produces "Zero".
Examples
digit_to_words(6) -> "Six"
number_to_words(17) -> "Seventeen"
number_to_words(804) -> "Eight Hundred Four"
number_to_words(3000020) -> "Three Million Twenty"
number_to_words(-91512) -> "Negative Ninety One Thousand Five Hundred Twelve"
Constraints
-2^31 <= num <= 2^31 - 1- Be ready to explain how you would support trillions, or a different language, with minimal changes.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
