모든 챌린지
보통 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

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위를 차지하세요.

다른 사람의 풀이 보기

커뮤니티 솔루션

아직 공개된 풀이가 없습니다. 문제를 풀고 첫 풀이를 공유하세요.