ง่าย 0 ข้อที่แก้แล้ว อัตราผ่าน 0%

Hours, Minutes, and Seconds

Convert a duration in seconds to a compact readable string.

สิ่งที่คุณจะได้เรียนรู้

  • Split seconds into hours, minutes and seconds
  • Use division and remainder together
  • Format parts into a readable string

โจทย์

ดูฉบับแปล

Split a duration into hours, minutes, and seconds. Write units as h, m, and s, in that order, with one space between units. Omit any zero-valued unit, except that zero seconds is written as 0s.

Implement format_duration(seconds).

Input

seconds: The total duration in seconds.

Output

Return the formatted duration, for example 2h 2m 5s.

เงื่อนไข

0 ≤ seconds ≤ 1,000,000,000. Hours may exceed 23; this is a duration, not a time of day.

ตัวอย่าง

ตัวอย่างที่ 1
อินพุต:
seconds = 7325

ผลลัพธ์ที่คาดหวัง:
expected = "2h 2m 5s"
อินพุต:
long long seconds = 7325;

ผลลัพธ์ที่คาดหวัง:
std::string expected = "2h 2m 5s";
อินพุต:
long seconds = 7325;

ผลลัพธ์ที่คาดหวัง:
string expected = "2h 2m 5s";

คำอธิบาย

7325 = 2 × 3600 + 2 × 60 + 5.

ตัวอย่างที่ 2
อินพุต:
seconds = 120

ผลลัพธ์ที่คาดหวัง:
expected = "2m"
อินพุต:
long long seconds = 120;

ผลลัพธ์ที่คาดหวัง:
std::string expected = "2m";
อินพุต:
long seconds = 120;

ผลลัพธ์ที่คาดหวัง:
string expected = "2m";

คำอธิบาย

120 seconds is exactly 2 minutes. Omit the zero hours and seconds.

แนวทางการแก้

ลองทำเองก่อน แล้วค่อยเปิดคำใบ้ทีละข้อ

คำใบ้ 1

Break the total seconds into larger units first, then format only the nonzero parts.

คำใบ้ 2

Keep hours, minutes, and seconds in that order, with spaces between included units.

คำใบ้ 3

If every larger unit is zero, still make sure the output is exactly 0s when the duration is zero.

ความซับซ้อนที่คาดหวัง

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

แหล่งอ้างอิง

โจทย์นี้ปรับให้เหมาะกับ CodeUtility กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน

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

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

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