Given a time in AM/PM format, convert it to military (24-hour) time.
Note: Midnight is 12:00:00AM on a 12-hour clock and 00:00:00 on a 24-hour clock. Noon is 12:00:00PM on a 12-hour clock and 12:00:00 on a 24-hour clock.
Input Format
A time in 12-hour clock format (i.e.: hh:mm:ssAM or hh:mm:ssPM), where 01≤hh≤12.
Output Format
Convert and print the given time in 24-hour format, where 00≤hh≤23.
Sample Input
07:05:45PM
Sample Output
19:05:45
Explanation
7 PM is after noon, so you need to add 12 hours to it during conversion. 12 + 7 = 19. Minutes and seconds do not change in 12-24 hour time conversions, so the answer is 19:05:45.
Solution:
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String time = in.next();
int hour = Integer.parseInt(time.substring(0,2));
if(time.contains("AM"))
{
if(hour == 12)
{
printMilitiaryTime(time, -12);
}else
{
printMilitiaryTime(time, 0);
}
}else if(time.contains("PM"))
{
if(hour == 12)
{
printMilitiaryTime(time, 0);
}else
{
printMilitiaryTime(time, 12);
}
}
}
private static void printMilitiaryTime(String time, Integer hrsToAdd)
{
Integer hour = Integer.parseInt(time.substring(0,2));
hour = hour + hrsToAdd;
String hrStr = "";
if(hour == 0)
{
hrStr = "00";
}else if(hour < 10)
{
hrStr = "0" + hour;
}else
{
hrStr = hour.toString();
}
System.out.print(hrStr + time.substring(2,time.length()-2));
}
}
Note: Midnight is 12:00:00AM on a 12-hour clock and 00:00:00 on a 24-hour clock. Noon is 12:00:00PM on a 12-hour clock and 12:00:00 on a 24-hour clock.
Input Format
A time in 12-hour clock format (i.e.: hh:mm:ssAM or hh:mm:ssPM), where 01≤hh≤12.
Output Format
Convert and print the given time in 24-hour format, where 00≤hh≤23.
Sample Input
07:05:45PM
Sample Output
19:05:45
Explanation
7 PM is after noon, so you need to add 12 hours to it during conversion. 12 + 7 = 19. Minutes and seconds do not change in 12-24 hour time conversions, so the answer is 19:05:45.
Solution:
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String time = in.next();
int hour = Integer.parseInt(time.substring(0,2));
if(time.contains("AM"))
{
if(hour == 12)
{
printMilitiaryTime(time, -12);
}else
{
printMilitiaryTime(time, 0);
}
}else if(time.contains("PM"))
{
if(hour == 12)
{
printMilitiaryTime(time, 0);
}else
{
printMilitiaryTime(time, 12);
}
}
}
private static void printMilitiaryTime(String time, Integer hrsToAdd)
{
Integer hour = Integer.parseInt(time.substring(0,2));
hour = hour + hrsToAdd;
String hrStr = "";
if(hour == 0)
{
hrStr = "00";
}else if(hour < 10)
{
hrStr = "0" + hour;
}else
{
hrStr = hour.toString();
}
System.out.print(hrStr + time.substring(2,time.length()-2));
}
}
0 comments:
Post a Comment