Convert seconds into hours, minutes, and seconds
Problem statement
A duration like a job's runtime often comes as a single number of seconds, which isn't easy to read at a glance. Breaking it into hours, minutes, and seconds uses two operators together: whole-number division to find how many full units fit, and % to find what's left over for the next unit.
Common mistake: in Python, using / instead of // for the hours and minutes step.
Wrong: hours = total_seconds / 3600/ gives a decimal, 1.0169..., which doesn't make sense as "1 hour." // throws away the decimal and keeps just the whole number of hours, 1. Java and C++ don't have this trap, dividing two int values already gives you a whole number automatically.
Your task: given totalSeconds = 3661, print it in the form <hours>h <minutes>m <seconds>s, with minutes and seconds padded to two digits.
Expected output:
1h 01m 01sApproach
hours = totalSeconds // 3600(Python) ortotalSeconds / 3600(Java/C++, since dividing twoints already drops the decimal).remainder = totalSeconds % 3600, the seconds left after removing full hours.minutes = remainder // 60(or/ 60), andseconds = remainder % 60.
Minutes and seconds are padded to two digits, 01 not 1, using each language's zero-padding format:
- Python:
f"{minutes:02d}" - Java:
String.format("%02d", minutes) - C++:
std::setfill('0') << std::setw(2) << minutes
total_seconds = 3661
hours = total_seconds // 3600
remainder = total_seconds % 3600
minutes = remainder // 60
seconds = remainder % 60
print(f"{hours}h {minutes:02d}m {seconds:02d}s")