中級 0件解決済み 正答率0%

Number to Words

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

このチャレンジで学べること

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

問題

翻訳を表示

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.

制約

0 ≤ n ≤ 999,999,999,999

例

例 1
入力:
n = 123

期待される出力:
expected = "one hundred twenty-three"
入力:
long long n = 123;

期待される出力:
std::string expected = "one hundred twenty-three";
入力:
long n = 123;

期待される出力:
string expected = "one hundred twenty-three";

解説

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

例 2
入力:
n = 12045

期待される出力:
expected = "twelve thousand forty-five"
入力:
long long n = 12045;

期待される出力:
std::string expected = "twelve thousand forty-five";
入力:
long n = 12045;

期待される出力:
string expected = "twelve thousand forty-five";

解説

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

解き方のヒント

まずは自分で考えてから、ヒントを 1 つずつ開いてみましょう。

ヒント 1

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

ヒント 2

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

ヒント 3

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

目安の計算量

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

参考資料

この課題はCodeUtility用に調整されています。上記の説明と制約に従ってください。

ランキング

全体ランキング

コーダーごとのいちばん良い合格解答です。速く、メモリが少なく、評価が高い解答ほど上位になります。

まだ合格した解答はありません。解いて 1 位になりましょう。

他の人の解答から学ぶ

コミュニティの解答

まだ公開された解答がありません。この課題を解いて最初の解答を共有しましょう。