코딩테스트 풀이/JAVA
[LeetCode/Easy] 1360. Number of Days Between Two Dates
무지맘
2023. 4. 11. 13:02
1. Input
1) String date1
2) String date2
2. Output
1) date1과 date2의 날짜 수 차이를 반환
3. Constraint
1) 주어지는 입력은 1971년부터 2100년 사이의 날짜이다.
4. Example
Input: date1 = "2019-06-29", date2 = "2019-06-30" -> Output: 1
Input: date1 = "2020-01-15", date2 = "2019-12-31" -> Output: 15
5. Code
1) 첫 코드(2023/04/11)
// 메인
int y1 = Integer.valueOf(date1.substring(0,4));
int y2 = Integer.valueOf(date2.substring(0,4));
int m1 = Integer.valueOf(date1.substring(5,7));
int m2 = Integer.valueOf(date2.substring(5,7));
int d1 = Integer.valueOf(date1.substring(8));
int d2 = Integer.valueOf(date2.substring(8));
return Math.abs(countdays(y1,m1,d1)-countdays(y2,m2,d2));
static int countdays(int year, int month, int day){
int[] md = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
for(int i=0 ; i<month-1 ; i++)
day += md[i];
for(int i=1971 ; i<year ; i++){
day += 365;
if(i%4==0){
if(i%100!=0) day++;
else if(i%400==0) day++;
}
}
if(month>2){
if(year%4==0){
if(year%100!=0) day++;
else if(year%400==0) day++;
}
}
return day;
}