[HackerRank - Java] Day 1 - 3. Time Conversion

2023. 1. 27. 14:09Java/coding test

반응형

Time Conversion

Given a time in 12-hour AM/PM format, convert it to military (24-hour) time.

Note:

  • 12:00:00AM on a 12-hour clock is 00:00:00 on a 24-hour clock.
  • 12:00:00PM on a 12-hour clock is 12:00:00 on a 24-hour clock.

Example

  • s = '12:01:00PM'
    • Return '12:01:00'.
  • s = '12:01:00AM'
    • Return '00:01:00'.

Function Description

Complete the timeConversion function in the editor below. It should return a new string representing the input time in 24 hour format.

timeConversion has the following parameter(s):

  • string s: a time in 12 hour format

Returns

  • string: the time in 24 hour format

Input Format

A single string that represents a time in 12-hour clock format (i.e.: or ).

Constraints

  • All input times are valid

Sample Input

07:05:45PM

Sample Output

19:05:45

12시간제로 표기된 입력값을 24시간제로 표기하기

01-2

출처: Wikipedia

AM이면서 12시일 경우 시간에서 12를 빼주고
PM이면서 12시가 아닐 경우 12를 더해주면 됩니다.

static String timeConversion(String s) {
    int hour = Integer.parseInt(s.substring(0, 2)), min = Integer.parseInt(s.substring(3, 5)), sec = Integer.parseInt(s.substring(6, 8));
    String meridium = s.substring(8);
    if ("AM".equals(meridium) && 12 == hour) {
        hour -= 12;
    } else if ("PM".equals(meridium) && 12 != hour) {
        hour += 12;
    }
    return String.format("%02d:%02d:%02d", hour, min, sec);
}
728x90
반응형