Problema
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 isthree hundred five. - Groups of three digits get the scale word
thousand,millionorbillion, and a group that is 0 is left out entirely: 1,000,005 isone million five. zerois used only when n is 0.
Input
n: A non-negative integer.
Output
Return the words as one string.
Vincoli
0 ≤ n ≤ 999,999,999,999
Esempi
Input:
n = 123
Output atteso:
expected = "one hundred twenty-three"
Input:
long long n = 123;
Output atteso:
std::string expected = "one hundred twenty-three";
Input:
long n = 123;
Output atteso:
string expected = "one hundred twenty-three";
Spiegazione
One hundred, then twenty and three joined by a hyphen: "one hundred twenty-three".
Input:
n = 12045
Output atteso:
expected = "twelve thousand forty-five"
Input:
long long n = 12045;
Output atteso:
std::string expected = "twelve thousand forty-five";
Input:
long n = 12045;
Output atteso:
string expected = "twelve thousand forty-five";
Spiegazione
The thousands group is 12 and the rest is 45: "twelve thousand forty-five".
Come affrontarlo
Prova prima da solo, poi apri un suggerimento alla volta.
Suggerimento 1
Write a helper that spells numbers from 1 to 999, then reuse it for each group.
Suggerimento 2
Groups go from billions down to units; skip a group that is zero.
Suggerimento 3
Keep separate word lists for 0 to 19 and for the tens.
Complessità attesa
O(1) time, O(1) extra space
Riferimenti
Questa sfida è adattata per CodeUtility. Segui la traccia e i vincoli sopra.