ปานกลาง 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 กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน

คำตอบที่ผ่านดีที่สุดของแต่ละคน คำตอบที่เร็วกว่า ใช้หน่วยความจำน้อยกว่า และได้คะแนนดีกว่าจะอยู่ด้านบน

ยังไม่มีคำตอบที่ผ่าน แก้โจทย์นี้แล้วคว้าอันดับหนึ่งไปเลย

เรียนรู้จากคนอื่น

แนวทางจากชุมชน

ยังไม่มีวิธีทำที่เผยแพร่ ลองแก้โจทย์นี้เพื่อแชร์วิธีแรก