문제
Given a time in -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
- Return '12:01:00'.
- 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 hour format
Returns
- string: the time in hour format
Input Format
A single string that represents a time in -hour clock format (i.e.: or ).
Constraints
- All input times are valid
- 입력 예시 -
// (case 1)
07:05:45PM
- 출력 예시 -
// (case 1)
19:05:45
정답 코드
< 내 정답 코드 >
class Result5 {
public static String timeConversion(String s) {
StringBuilder sb = new StringBuilder();
boolean isAm = s.substring(8).equals("AM") ? true : false;
int hour = Integer.parseInt(s.substring(0, 2));
String minuteAndSecond = s.substring(2, 8);
if (isAm && hour == 12) {
sb.append("00").append(minuteAndSecond);
return new String(sb);
}
if (isAm) {
return String.format("%02d%s", hour, minuteAndSecond);
}
if (hour == 12) {
sb.append("12").append(minuteAndSecond);
return new String(sb);
}
return String.format("%02d%s", hour + 12, minuteAndSecond);
}
}
< 타인 답변 코드 >
public class Question5 {
public static String timeConversion(String s) {
String[] time = s.substring(0, s.length() - 2).split(":");
Integer hour = Integer.parseInt(time[0]);
String minute = time[1];
String second = time[2];
String formatAmPm = s.substring(s.length() - 2);
if (formatAmPm.equals("PM")) {
return pmTimeFormat(hour, minute, second);
}
if (formatAmPm.equals("AM")) {
return amTimeFormat(hour, minute, second);
}
return null;
}
private static String amTimeFormat(Integer hour, String minute, String second) {
if (hour != 12) {
return String.format("%02d", hour) + ":" + minute + ":" + second;
}
return String.format("%02d", 0) + ":" + minute + ":" + second;
}
private static String pmTimeFormat(Integer hour, String minute, String second) {
if (hour != 12) {
return (hour + 12) + ":" + minute + ":" + second;
}
return String.format("%02d", hour) + ":" + minute + ":" + second;
}
}
이것을 주의하자!
- int 형 ' 07 ' 은 0 이 사라져서 ' 7 ' 로 출력된다. 하지만 시계 기능에선 앞의 ' 0 ' 도 함께 출력할 필요가 있다. 그럴때 String.format( ) 을 사용하면 된다. %d 형식에서 자릿수와 함께 빈칸을 ' 0 ' 으로 채울 수 있기 때문이다.
- 타인의 코드를 보면 아예 배열을 이용해서 ' 시 ' : ' 분 ' : ' 초 ' 를 나눴다. 훨씬 깔끔하고 가독성이 좋아 보인다.
- PM 또는 AM 인지 확인하는 방법 중 하나는 .contains( ) 을 이용해서 true, false 를 반환할 수 있다.
- 배열에 있는 원소를 String 으로 변환하는 방법에 String.join( ) 이 있다. 매개변수로 구분자와 배열 또는 리스트를 넣어주면 해당 구분자를 기준으로 String 을 만든다.
'코딩 테스트' 카테고리의 다른 글
[LeetCode] (Medium) Reverse Integer * (0) | 2022.11.23 |
---|---|
[LeetCode] (Easy) Two Sum ** (0) | 2022.11.23 |
[Hacker Rank] (Easy) Grading Students (0) | 2022.11.20 |
[Hacker Rank] (Easy) Compare the Triplets (0) | 2022.11.20 |
[백준] (14681번) 사분면 고르기 (0) | 2022.11.19 |