← Questions

Integer to English words, built up by range

0
MicrosoftCoding

A coding interview question asked at Microsoft. It tests strings, math and recursion.

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.

Clarifying questions

  • Should digit_to_words accept bool or a float such as 3.0, or only int?
  • Is the output always "Title Case", and must "One Hundred" include "One"?
  • Must the later parts keep digit_to_words and the 0-99 helper as public functions, or only number_to_words?
  • Is "Negative Zero" ever expected? (It should not be.)

What a strong answer covers

  • Has one helper for 0-999 that is built from the digit and the two-digit helpers. It treats 10-19 and the tens words as tables, not as rules.
  • number_to_words splits the absolute value into groups of three digits from the right. It joins each non-zero group with its scale word and skips zero groups, so 3,000,020 has no "Thousand".
  • Takes the absolute value safely for -2^31, and returns "Zero" only for 0.
  • Keeps the scale words in a list, so trillions need one more entry and no new logic.
  • Tests 0, 10-19, every multiple of ten, 100, 1,000,000, 1,000,001, 2^31 - 1 and -2^31.

Follow-ups

  • British English, with "and" after hundreds ("One Hundred and Four").
  • Another language with different grouping or gendered words. Discuss which parts move into data.
  • The reverse: parse the words back into a number, and reject invalid phrases.
  • Ordinal words ("Twenty First").

Where it's asked

What it tests

strings · math · recursion · extensibility

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