1. Time to Time (흐른 시간 계산)
2시 5분에서 4시 1분이 되려면 몇 분이 흘러야 하는지 계산하려면, 시뮬레이션을 이용하여 구할 수 있습니다.
1분 단위로 시뮬레이션을 하며, 60분이 되면 시간을 늘리고 분을 0으로 맞추면 됩니다.
public class Main {
public static void main(String[] args) {
int hour = 2, mins = 5;
int elapsedTime = 0;
while(true) {
if(hour == 4 && mins == 1)
break;
elapsedTime++;
mins++;
if(mins == 60) {
hour++;
mins = 0;
}
}
System.out.print(elapsedTime);
}
}
하지만, 더 간단히 구하는 방법도 있습니다.
0시 0분에서 시작하여 각 시간까지 걸리는 시간(분)을 계산하고,
그 차이를 계산하면 됩니다.
아래에서 코드에서는 getMinute 함수가 00:00에서 걸리를 시간을 계산해줍니다.
import java.io.*;
import java.util.*;
public class Main {
public static int getMinute(int h, int m) {
return h * 60 + m;
}
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 d = sc.nextInt();
System.out.println(getMinute(c,d)-getMinute(a, b));
}
}
2. Date to Date (흐른 날짜 계산)
2월 5일에서 4월 1일 사이에 몇 일이 있는지 계산하려면, 시뮬레이션을 이용하여 구할 수 있습니다.
1일 단위로 시뮬레이션을 하며, 해당 월에 있는 일 수를 넘어가게 되면, 다음 달로 넘기고 일을 1로 맞추면 됩니다.
(각 월마다 몇 일이 있는지 배열에 미리 정의하면 간결하게 구현할 수 있습니다.)
public class Main {
public static void main(String[] args) {
int month = 2, day = 5;
int elapsedDays = 0;
// 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12.
int[] num_of_days = new int[]{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
while(true) {
if(month == 4 && day == 1)
break;
elapsedDays++;
day++;
if(day > num_of_days[month]) {
month++;
day = 1;
}
}
System.out.print(elapsedDays);
}
}
하지만, 흐른 날짜 또한 더 간단히 구하는 방법도 있습니다.
1월 1일에서 시작하여 각 날짜까지 몇 일이 있는지 계산하고,
그 차이를 계산하면 됩니다.
아래에서 코드에서는 getDay 함수가 1월 1일에서 걸리를 일을 계산해줍니다.
import java.io.*;
import java.util.*;
public class Main {
// 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12
public static int[] endOfMonth = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
public static int getDay(int m, int d) {
int elapsedDays = 0;
for (int i = 0; i < m; i++) {
elapsedDays += endOfMonth[i];
}
elapsedDays += d;
return elapsedDays;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int m1 = sc.nextInt();
int d1 = sc.nextInt();
int m2 = sc.nextInt();
int d2 = sc.nextInt();
// 첫 날도 포함하므로 +1을 해줍니다.
System.out.println(getDay(m2, d2) - getDay(m1, d1) + 1);
}
}
💡요약
흐른 시간이나 일수를 간단히 계산하려면,
기준점과의 차이를 먼저 계산한 뒤, 두 날짜(시간)의 차이를 계산하면 된다 ❕❕❕

'ALGORITHM' 카테고리의 다른 글
| 구간 칠하기 (0) | 2025.04.17 |
|---|---|
| 십진수를 2진수로, n진수를 m 진수로 - 진수 변환 [알고리즘/JAVA] (1) | 2025.04.11 |
| [알고리즘] 비트마스크 (Bitmask) (1) | 2024.12.24 |
| [Algorithm] 이분탐색 알고리즘 - Upper Bound/Lower Bound (0) | 2024.12.08 |
| [JAVA] Arrays.sort 와 Collections.sort의 차이 (1) | 2024.12.04 |