https://www.acmicpc.net/problem/2525

이번에도 생각나는대로 적어보았다.
처음 생각한 풀이과정(틀림)
- a b c가 있을 때 b + c < 60이라면 그대로 출력
- b+c = 60 이라면 a + 1, b = 0
- b+c > 60 * i 일 땐 b+c i 가 1이라면 a+1, i가 2라면 a+2, 그리고 b = b+c - 60로 업데이트
import java.util.*
public class Main {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
int i = (b + c) / 60;
if (b + c < 60) {
b = b + c;
System.out.println(a);
System.out.println(b);
} else if (b + c == 60) {
b = 0;
a++;
System.out.println(a);
System.out.println(b);
} else if (b + c > 60) {
a = a + i;
b = (b + c) - 60;
System.out.println(a);
System.out.println(b);
}
sc.close();
}
}
틀렸다!
왜 틀렸을까...!
틀린 이유 분석
a(시간)가 24 이상이 될 경우를 고려하지 않음
현재 코드에서는 a + i가 24 이상이 되더라도 0~23 범위로 조정하지 않음.
하지만 24시가 되면 0시로 돌아가야 함.
✅ 해결 방법
a = (a + i) % 24를 사용해서 24 이상이 되면 0~23 범위로 조정해야 함.
너무 어렵게 생각한 것 같다.
시간을 분으로 바꿔서 다시 생각해보면, 모든 시간을 더한 후 나머지 연산(%)을 사용하여 시와 분을 찾을 수 있다.
import java.util.*;
public class Main {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int a = sc.nextInt(); // 현재 시
int b = sc.nextInt(); // 현재 분
int c = sc.nextInt(); // 걸리는 시간
int min = a * 60 + b + c; // 전체 분 계산
a = (min / 60) % 24;
b = min % 60;
System.out.println(a + " " + b);
sc.close();
}
}
정답이다!
앞으로는 좀 더 생각해보고 작성해야겠다.
'IT > coding test' 카테고리의 다른 글
| [Java] 백준 - 2480 (1) | 2025.03.25 |
|---|---|
| [Java] 백준 - 2884 (0) | 2025.01.29 |
| [Java] 백준 - 14681 (0) | 2025.01.29 |
| [Java] 백준 - 2753 (0) | 2025.01.28 |
| [Java] 백준 - 9498 (0) | 2025.01.28 |