← Questions

Integer to English words, built up by range

0
MicrosoftCoding

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.

  1. Digits. digit_to_words(n) for 0 <= n <= 9. Raise an error for anything else.
  2. Two digits. Extend to 0 <= n <= 99. Watch the irregular words for 10-19.
  3. Three digits. Extend to 0 <= n <= 999.
  4. Full range. number_to_words(num) for any 32-bit signed integer, using the scale words Thousand, Million and Billion.
  5. 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.
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