Retour aux défis
Facile 0 résolus 0 % de réussite

Hours, Minutes, and Seconds

Convert a duration in seconds to a compact readable string.

Ce que vous allez apprendre

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

Problème

Afficher la traduction

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.

Contraintes

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

Exemples

Exemple 1
Entrée :
seconds = 7325

Sortie attendue :
expected = "2h 2m 5s"
Entrée :
long long seconds = 7325;

Sortie attendue :
std::string expected = "2h 2m 5s";
Entrée :
long seconds = 7325;

Sortie attendue :
string expected = "2h 2m 5s";

Explication

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

Exemple 2
Entrée :
seconds = 120

Sortie attendue :
expected = "2m"
Entrée :
long long seconds = 120;

Sortie attendue :
std::string expected = "2m";
Entrée :
long seconds = 120;

Sortie attendue :
string expected = "2m";

Explication

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

Comment l'aborder

Essayez d'abord seul, puis ouvrez les indices un par un.

Indice 1

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

Indice 2

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

Indice 3

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

Complexité attendue

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

Références

Ce défi a été adapté pour CodeUtility. Suivez l'énoncé et les contraintes ci-dessus.

Apprenez des autres

Solutions de la communauté

Aucune solution publiée pour l'instant. Résolvez ce défi pour partager la première.