Intermedio 0 resueltos 0% de aceptación

Number to Words

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

Lo que aprenderás

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

Problema

Ver traducción

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.

Restricciones

0 ≤ n ≤ 999,999,999,999

Ejemplos

Ejemplo 1
Entrada:
n = 123

Salida esperada:
expected = "one hundred twenty-three"
Entrada:
long long n = 123;

Salida esperada:
std::string expected = "one hundred twenty-three";
Entrada:
long n = 123;

Salida esperada:
string expected = "one hundred twenty-three";

Explicación

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

Ejemplo 2
Entrada:
n = 12045

Salida esperada:
expected = "twelve thousand forty-five"
Entrada:
long long n = 12045;

Salida esperada:
std::string expected = "twelve thousand forty-five";
Entrada:
long n = 12045;

Salida esperada:
string expected = "twelve thousand forty-five";

Explicación

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

Cómo abordarlo

Inténtalo primero por tu cuenta y luego abre las pistas una a una.

Pista 1

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

Pista 2

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

Pista 3

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

Complejidad esperada

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

Referencias

Este reto está adaptado para CodeUtility. Sigue el enunciado y las restricciones indicadas arriba.

Clasificación

Clasificación completa

La mejor solución aprobada de cada programador. Las más rápidas, ligeras y mejor valoradas van primero.

Aún no hay soluciones aprobadas. Resuélvelo y quédate el primer puesto.

Aprende de otros

Soluciones de la comunidad

Aún no hay soluciones publicadas. Resuelve este reto para compartir la primera.