Torna alle sfide
Facile 0 risolte 0% di accettazione

Hours, Minutes, and Seconds

Convert a duration in seconds to a compact readable string.

Cosa imparerai

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

Problema

Mostra traduzione

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.

Vincoli

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

Esempi

Esempio 1
Input:
seconds = 7325

Output atteso:
expected = "2h 2m 5s"
Input:
long long seconds = 7325;

Output atteso:
std::string expected = "2h 2m 5s";
Input:
long seconds = 7325;

Output atteso:
string expected = "2h 2m 5s";

Spiegazione

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

Esempio 2
Input:
seconds = 120

Output atteso:
expected = "2m"
Input:
long long seconds = 120;

Output atteso:
std::string expected = "2m";
Input:
long seconds = 120;

Output atteso:
string expected = "2m";

Spiegazione

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

Come affrontarlo

Prova prima da solo, poi apri un suggerimento alla volta.

Suggerimento 1

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

Suggerimento 2

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

Suggerimento 3

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

Complessità attesa

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

Riferimenti

Questa sfida è adattata per CodeUtility. Segui la traccia e i vincoli sopra.

Impara dagli altri

Soluzioni della community

Nessuna soluzione pubblicata. Risolvi questa sfida per condividere la prima.