- 실수 원인: 자정부터의 시간 계산을 누락!!
- 문제 분석/해석
- 문제: hh:mm:ss 포맷의 두 시각의 차이를 hh:mm:ss 포맷으로 출력하기
1. 콜론(:) 문자를 기준으로 시간, 분, 초를 쪼갬
// substring 사용
String time = "09:00:19";
int hour = Integer.parseInt(time.substring(0,2));
int minute = Integer.parseInt(time.substring(3,5));
int second = Integer.parseInt(time.substring(6,8));
// split 사용
String[] time = "09:00:19".split(":");
int hour = Integer.parseInt(time[0]);
int minute = Integer.parseInt(time[1]);
int second = Integer.parseInt(time[2]);
2. 각각의 두 시간, 분, 초 차이를 계산
/// 계층적으로 표현되는 각 단위를 계산할 때, 가장 작은 단위로 통일하면 더 편하게 계산 가능(초)
/*
1000초 = 3600 * (2시간) + 2800초
= 2시간 + 60 * (46분) + 40초
= 2시간 46분 40초
*/
int currentSecondAmount = currentHour * 3600 + currentMinute * 60 + currentSecond;
int targetSecoundAmount = targetHour * 3600 + targetMinute * 60 + targetSecond;
int needSecondAmount = targetSecondAmount - currentSecondAmount;
if(needSecondAmount < 0) needSecondAmont += 24 * 3600; // 자정이 넘는경우 별도 계산
int needHour = needSecondAmount / 3600;
int needMinute = (needSecondAmount % 3600) / 60;
int needSecond = needSecondAmount % 60;
3. 구해진 시간을 hh:mm:ss 형태로 출력
문자열 포맷 코드 | 설명 |
%s | 문자열 |
%c | 문자 1개 |
%d | 정수 |
%f | 부동소수 |
%o | 8진수 |
%x | 16진수 |
%% | Literal % (문자 % 대체) |
String ans = String.format("%02d:%02d:%02d", h, m, s);
System.out.println(ans);
또는
System.out.printf("%02d:%02d:%02d", h, m, s);
- 내 코드
mport java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String now_time = sc.nextLine();
String put_time = sc.nextLine();
// 콜론을 기준으로 배열에 담아줌
String time1[] = now_time.split(":");
String time2[] = put_time.split(":");
// 정수형으로 시분초 변환
int h1 = Integer.parseInt(time1[0]); // hh
int m1 = Integer.parseInt(time1[1]); // mm
int s1 = Integer.parseInt(time1[2]); // ss
int h2 = Integer.parseInt(time2[0]);
int m2 = Integer.parseInt(time2[1]);
int s2 = Integer.parseInt(time2[2]);
// 시,분을 초로 변환 (1시간 3600초, 1분 60초)
int second1 = (h1 * 3600) + (m1 * 60) + s1;
int second2 = (h2 * 3600) + (m2 * 60) + s2;
// put_time(second2)가 now_time(second1) 보다 작으면 다음 날로 간주
if(second2 < second1){
second2 += 24 * 3600; // 24시간을 초로 변환(3600초) 한걸 더해줌
}
int diff = second2 - second1; // 차이 계산
if (diff == 0) diff = 24 * 3600; // 0초면 24시간으로
// 초를 다시 시분초로 변환
int h = diff / 3600;
int m = (diff % 3600) / 60;
int s = diff % 60;
System.out.printf("%02d:%02d:%02d\n", h, m, s);
}
}
- 핵심 개념 / 알고리즘:
- substring
- split
- 문자열 포맷코드
- 개선점 / 주의할 점:
- 자정 이후 시간 계산 유의하기
'스터디 > 알고리즘' 카테고리의 다른 글
[백준 1543] 문서 검색 (0) | 2025.07.30 |
---|---|
[백준 1157] 단어 공부 (0) | 2025.07.30 |
[백준 1919] 애너그램 만들기 (0) | 2025.07.30 |
[백준 2744] 대소문자 바꾸기 (0) | 2024.08.06 |
[백준 11655] ROT13 (0) | 2022.06.21 |