KatInterview

Convert Integer to English Words

StringsAuto-graded · 30 test cases
EasyAuto-gradedStringsrecursionmathstring-formatting

Last updated

Tests ability to decompose integers into groups and translate numeric values into properly formatted English text with correct scaling terms.

Write a function that converts a nonnegative integer into its English words representation.

Your function must handle all integers from 0 to 2,147,483,647 (inclusive).

Rules:

  • The input 0 should produce "Zero"
  • Use American English scale terms: Thousand, Million, Billion
  • Do not include the word and anywhere in the output
  • Separate words with single spaces; no leading or trailing whitespace
  • Capitalize the first letter of each word exactly as shown below

Constraints:

  • 0 ≤ num ≤ 2,147,483,647

Examples

Example 1

Input: number_to_words(7)

Output: 'Seven'

Example 2

Input: number_to_words(19)

Output: 'Nineteen'

Example 3

Input: number_to_words(123)

Output: 'One Hundred Twenty Three'

Example 4

Input: number_to_words(1005)

Output: 'One Thousand Five'

Example 5

Input: number_to_words(1234567)

Output: 'One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven'

Example 6

Input: number_to_words(2147483647)

Output: 'Two Billion One Hundred Forty Seven Million Four Hundred Eighty Three Thousand Six Hundred Forty Seven'

Hints

Hint 1

Think of the number as groups of three digits from right to left, each with an optional scale word (Thousand, Million, Billion).

Hint 2

Build a helper function that converts any number from 1 to 999 into words—this handles the irregular patterns for tens and teens.

Hint 3

Collect all word parts in a list and join them at the end to avoid stray spaces.