요구사항
주어진 두 시간(시, 분, 초) 사이에 초침과 시침/분침이 만나는 횟수 구하기
(초침, 시침, 분침이 한번에 만나는 경우 1회로 count)
입력 값
int h1, m1, s1 | 시작 시간, 분, 초 |
int h2, m2, s2 | 종료 시간, 분, 초 |
풀이
1. 시작 시간의 각(시/분/초) 침의 위치 구하기
-> 0에서 60 사이의 double 형으로 지정
2. 시작 시간의 초침과 시/분 침이 만나있는 경우 알람 count + 1
3. 시작 시간에서 1초 씩 더해가며 초침과 시/분 침이 만날 경우 count
-> 초침이 시/분침보다 1칸 미만 작은 경우 1초 후엔 초침이 시/분침을 넘어가므로 알람 count + 1
-> 시/분/초 침이 한번에 만나는 0시 정각과 12시 정각의 경우 중복 카운팅 방지를 위해 count - 1
4. 알람 count return
728x90
Java 코드
class Solution {
public int solution(int h1, int m1, int s1, int h2, int m2, int s2) {
int answer = -1;
// 침 위치
double positionH = getPosition(h1, m1, s1);
double positionM = getPosition(m1, s1);
double positionS = getPosition(s1);
// 이동 후 시간
int nowH = h1;
int nowM = m1;
int nowS = s1;
int alarmCount = 0;
// 시작 위치 같은 경우도 count 필요
if(positionS == positionM || positionS == positionH) alarmCount++;
while(nowH != h2 || nowM != m2 || nowS != s2) {
// 초침이 분침보다 1칸 미만 차이일때
if(positionS < positionM && (positionM - positionS < 1)) alarmCount++;
// 초침이 시침보다 1칸 미만 차이일때
if(positionS < positionH && (positionH - positionS < 1)) alarmCount++;
// 시분초 모두 만나는 정오는 제외
if((nowH == 11 || nowH == 23) && nowM == 59 && nowS == 59) alarmCount--;
// 현재 시간 설정
nowH = (nowH + ((nowM + (nowS + 1) / 60) / 60));
nowM = (nowM + ((nowS + 1) / 60)) % 60;
nowS = (nowS + 1) % 60;
// 침 위치 재 설정
positionH = getPosition(nowH, nowM, nowS);
positionM = getPosition(nowM, nowS);
positionS = getPosition(nowS);
}
answer = alarmCount;
return answer;
}
private double getPosition(int h, int m, int s){
double movement = 1.0 / (60*60);
return (h + (((m * 60) + s) * movement)) * 5 % 60;
}
private double getPosition(int m, int s){
double movement = 1.0 / 60;
return m + (s * movement);
}
private double getPosition(int s){
double movement = 1;
return s * movement;
}
}
문제 출처
https://school.programmers.co.kr/learn/courses/30/lessons/250135
728x90
반응형
'코딩테스트 > PCCP' 카테고리의 다른 글
[프로그래머스] [PCCP 기출문제] 3번 / 충돌위험 찾기 (Java) (1) | 2025.02.18 |
---|---|
[프로그래머스] [PCCP 기출문제] 2번 / 퍼즐 게임 챌린지 (Java) (2) | 2025.02.17 |
[프로그래머스] [PCCP 기출문제] 2번 / 석유 시추 (Java) (1) | 2025.02.17 |
[프로그래머스] [PCCP 기출문제] 1번 / 붕대 감기 (Java) (0) | 2025.02.17 |
[프로그래머스] [PCCP 기출문제] 1번 / 동영상 재생기 (Java) (0) | 2025.02.17 |