Tous les défis
Moyen 0 résolus 0 % de réussite

Number to Words

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

Ce que vous allez apprendre

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

Problème

Afficher la traduction

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.

Contraintes

0 ≤ n ≤ 999,999,999,999

Exemples

Exemple 1
Entrée :
n = 123

Sortie attendue :
expected = "one hundred twenty-three"
Entrée :
long long n = 123;

Sortie attendue :
std::string expected = "one hundred twenty-three";
Entrée :
long n = 123;

Sortie attendue :
string expected = "one hundred twenty-three";

Explication

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

Exemple 2
Entrée :
n = 12045

Sortie attendue :
expected = "twelve thousand forty-five"
Entrée :
long long n = 12045;

Sortie attendue :
std::string expected = "twelve thousand forty-five";
Entrée :
long n = 12045;

Sortie attendue :
string expected = "twelve thousand forty-five";

Explication

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

Comment l'aborder

Essayez d'abord seul, puis ouvrez les indices un par un.

Indice 1

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

Indice 2

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

Indice 3

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

Complexité attendue

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

Références

Ce défi a été adapté pour CodeUtility. Suivez l'énoncé et les contraintes ci-dessus.

La meilleure solution validée de chaque codeur. Les plus rapides, les plus légères et les mieux notées passent devant.

Aucune solution validée pour l'instant. Résolvez-le et prenez la première place.

Apprenez des autres

Solutions de la communauté

Aucune solution publiée pour l'instant. Résolvez ce défi pour partager la première.