[LeetCode] Day of the Year

아르당·6일 전

LeetCode

목록 보기
244/254
post-thumbnail

문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음

Problem

YYYY-MM-DD 형식의 그레고리력 날짜를 나타내는 문자열 date가 주어졌을 때, 해당 연도 날짜의 수를 반환해라.

Example

#1
Input: date = "2019-01-09"
Output: 9
Explanation: 주어진 date는 2019년의 9번째 일이다.

#2
Input: date = "2019-02-10"
Output: 41

Constraints

  • date.length == 10
  • date[4] == date[7] == '-'이고, 다른 모든 날짜[i]는 숫자이다.
  • date는 1900년 1월 1일부터 2019년 12월 31일 사이를 나타낸다.

Solved

class Solution {
    public int dayOfYear(String date) {
        int[] days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
        int year = Integer.parseInt(date.substring(0, 4));
        int month = Integer.parseInt(date.substring(5, 7));
        int day = Integer.parseInt(date.substring(8, 10));

        if(isLeap(year)){
            days[1] = 29;
        }

        int total = 0;
        
        for(int i = 0; i < month - 1; i++){
            total += days[i];
        }

        total += day;

        return total;
    }

    private boolean isLeap(int year){
        return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
    }
}
profile
내 마음대로 코드 작성하는 세상

0개의 댓글