Say a duration the way a person would
A ticket screen shows how long something took, and "90m" reads worse than "1h 30m".
- Hours and minutes, separated by a single space: 90 becomes "1h 30m".
- Drop the part that is zero: 120 is "2h", 45 is "45m".
- Zero, or anything negative, is "0m".
minutesToText(minutes: int) → string
C++ needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.
Where you start
std::string minutesToText(int minutes) {
}
Worked examples
| Call | Result |
|---|---|
minutesToText(90) | std::string("1h 30m") |
minutesToText(120) | std::string("2h") |
minutesToText(45) | std::string("45m") |
minutesToText(0) | std::string("0m") |
Hint
Work out both parts, then decide which ones to print.
Reference solution in C++
std::string minutesToText(int minutes) {
if (minutes <= 0) return "0m";
int h = minutes / 60, m = minutes % 60;
if (h == 0) return std::to_string(m) + "m";
if (m == 0) return std::to_string(h) + "h";
return std::to_string(h) + "h " + std::to_string(m) + "m";
}