24-Hour to 12-Hour Clock
Problem
Read a time in the 24-hour form HH:MM. Print it in the 12-hour form h:MM AM or h:MM PM. Midnight 00:00 is 12:00 AM. Noon 12:00 is 12:00 PM. The hour has no leading zero, the minutes always have two digits.
Constraints
- 00:00 <= time <= 23:59
Examples
Input
13:05
Output
1:05 PM
Input
00:30
Output
12:30 AM
Solutions
The 12-hour clock has no hour 0: both midnight and noon show 12. So we use hour % 12 and replace 0 by 12. AM or PM comes from the original hour.
/*
* Problem : Process text.
* Input : One line of text.
* Output : The 12-hour time.
* Approach: Modulo 12.
* 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(String s) {
// Step 1: Split the text at the colon. Read the hour and the minutes as numbers.
String[] part = s.trim().split(":");
int hour = Integer.parseInt(part[0]);
int minute = Integer.parseInt(part[1]);
// Step 2: AM is before 12:00, PM is from 12:00. The 12-hour value is hour % 12, but 0 is shown as 12.
String suffix = hour < 12 ? "AM" : "PM";
int shown = hour % 12 == 0 ? 12 : hour % 12;
// Step 3: %02d writes the minutes with two digits.
return String.format("%d:%02d %s", shown, minute, suffix);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String s = scanner.hasNextLine() ? scanner.nextLine() : "";
System.out.println(solve(s));
}
}
Hints (1)
- What does 00:00 become?