Dễ 0 đã giải Tỷ lệ chấp nhận 0%

Hours, Minutes, and Seconds

Convert a duration in seconds to a compact readable string.

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

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

Đề bài

Xem bản dịch

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.

Ràng buộc

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

Ví dụ

Ví dụ 1
Đầu vào:
seconds = 7325

Kết quả mong đợi:
expected = "2h 2m 5s"
Đầu vào:
long long seconds = 7325;

Kết quả mong đợi:
std::string expected = "2h 2m 5s";
Đầu vào:
long seconds = 7325;

Kết quả mong đợi:
string expected = "2h 2m 5s";

Giải thích

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

Ví dụ 2
Đầu vào:
seconds = 120

Kết quả mong đợi:
expected = "2m"
Đầu vào:
long long seconds = 120;

Kết quả mong đợi:
std::string expected = "2m";
Đầu vào:
long seconds = 120;

Kết quả mong đợi:
string expected = "2m";

Giải thích

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

Hướng tiếp cận

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

Gợi ý 1

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

Gợi ý 2

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

Gợi ý 3

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

Độ 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.

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.