Seconds to Clock Format
Problem
Convert a number of seconds into hours, minutes and seconds. Print them as HH:MM:SS with two digits each (more digits for hours if needed). For 3661 the output is 01:01:01.
Constraints
- 0 <= n <= 359999
Examples
Input
3661
Output
01:01:01
Solutions
Integer division gives whole units and the remainder (%) gives what is left. We do this for hours first, then minutes. O(1).
/*
* Problem : Clock format.
* Input : Seconds.
* Output : HH:MM:SS.
* Approach: Division and remainder.
* Time : O(1)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static String solve(long n) {
// Step 1: One hour is 3600 seconds. The rest after the hours is less than 3600.
long hours = n / 3600;
// Step 2: One minute is 60 seconds. Use the remainder (%) to find the rest after the hours.
long minutes = n % 3600 / 60;
// Step 3: The seconds are what is left after whole minutes.
long seconds = n % 60;
return String.format("%02d:%02d:%02d", hours, minutes, seconds);
}
public static void main(String[] args) {
long n = new Scanner(System.in).nextLong();
System.out.println(solve(n));
}
}
Hints (2)
- How many seconds are in an hour?
- What does n % 60 give?