Format uptime

See the original problem on HackerRank.

Solutions

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
unsigned elapsed; cin >> elapsed;
static constexpr std::array<std::pair<int, std::string_view>, 4> units{ {
    {24*3600, "d "},
    {3600, "h "},
    {60, "m "},
    {1, "s"},
} };
std::string uptime;
for (const auto& [ratio, unit] : units)
{
    uptime += std::to_string(elapsed / ratio).append(unit);
    elapsed %= ratio;
}
std::cout << uptime << "\n";
comments powered by Disqus