Medium 0 solved 0% acceptance

Number to Words

Spell a whole number in English words, such as "one hundred twenty-three".

What you'll learn

  • Split a number into groups of three digits
  • Spell any number below 1000
  • Join word parts with exact spacing rules

Problem

Checks and invoices often show an amount in words. Write the number n in American English using these exact rules:

Implement number_to_words(n).

  • All letters are lowercase and words are separated by a single space. There is no "and" and there are no commas.
  • 0 to 19: zero, one, … nineteen. Tens: twenty, thirty, forty, fifty, sixty, seventy, eighty, ninety.
  • A tens word and a units word are joined with a hyphen: 42 is forty-two.
  • Hundreds are written as <digit> hundred: 305 is three hundred five.
  • Groups of three digits get the scale word thousand, million or billion, and a group that is 0 is left out entirely: 1,000,005 is one million five.
  • zero is used only when n is 0.

Input

n: A non-negative integer.

Output

Return the words as one string.

Constraints

0 ≤ n ≤ 999,999,999,999

Examples

Example 1
Input:
n = 123

Expected output:
expected = "one hundred twenty-three"
Input:
long long n = 123;

Expected output:
std::string expected = "one hundred twenty-three";
Input:
long n = 123;

Expected output:
string expected = "one hundred twenty-three";

Explanation

One hundred, then twenty and three joined by a hyphen: "one hundred twenty-three".

Example 2
Input:
n = 12045

Expected output:
expected = "twelve thousand forty-five"
Input:
long long n = 12045;

Expected output:
std::string expected = "twelve thousand forty-five";
Input:
long n = 12045;

Expected output:
string expected = "twelve thousand forty-five";

Explanation

The thousands group is 12 and the rest is 45: "twelve thousand forty-five".

How to approach it

Try on your own first, then open one hint at a time.

Hint 1

Write a helper that spells numbers from 1 to 999, then reuse it for each group.

Hint 2

Groups go from billions down to units; skip a group that is zero.

Hint 3

Keep separate word lists for 0 to 19 and for the tens.

Expected complexity

O(1) time, O(1) extra space

References

This challenge is adapted for CodeUtility. Follow the statement and constraints above.

The best passing solution of each coder. Faster, smaller and better-reviewed solutions rank higher.

No passing solutions yet. Solve it to take first place.

Learn from others

Community solutions

No published solutions yet. Solve this challenge to share the first one.