Trung bình 0 đã giải Tỷ lệ chấp nhận 0%

Number to Words

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

Bạn sẽ học được gì

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

Đề bài

Xem bản dịch

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.

Ràng buộc

0 ≤ n ≤ 999,999,999,999

Ví dụ

Ví dụ 1
Đầu vào:
n = 123

Kết quả mong đợi:
expected = "one hundred twenty-three"
Đầu vào:
long long n = 123;

Kết quả mong đợi:
std::string expected = "one hundred twenty-three";
Đầu vào:
long n = 123;

Kết quả mong đợi:
string expected = "one hundred twenty-three";

Giải thích

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

Ví dụ 2
Đầu vào:
n = 12045

Kết quả mong đợi:
expected = "twelve thousand forty-five"
Đầu vào:
long long n = 12045;

Kết quả mong đợi:
std::string expected = "twelve thousand forty-five";
Đầu vào:
long n = 12045;

Kết quả mong đợi:
string expected = "twelve thousand forty-five";

Giải thích

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

Hướng tiếp cận

Hãy tự thử trước, sau đó mở từng gợi ý một.

Gợi ý 1

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

Gợi ý 2

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

Gợi ý 3

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

Độ phức tạp mong đợi

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

Tham khảo

Thử thách này đã được điều chỉnh cho CodeUtility. Hãy làm theo đề bài và các ràng buộc ở trên.

Lời giải đạt tốt nhất của mỗi người. Lời giải nhanh hơn, tốn ít bộ nhớ hơn và được đánh giá cao hơn sẽ đứng trên.

Chưa có lời giải nào đạt. Giải bài này để giành hạng nhất.

Học hỏi từ người khác

Giải pháp cộng đồng

Chưa có giải pháp nào được chia sẻ. Hãy giải thử thách này để đăng giải pháp đầu tiên.