잡다한 코딩/Project Euler (Java)

(Java) Project Euler 019 - Counting Sundays

Skyleester_devNurse 2023. 12. 28. 18:00
// You are given the following information, but you may prefer to do some research for yourself.

//  - 1 Jan 1900 was a Monday.
//  - Thirty days has September, April, June, and November.
//  - All the rest have thirty-one,
//  - Saving February alone,
//  - Which has twenty-eight, rain or shine.
//  - And on leap years, twenty-nine.
//  - A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.

// How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?

 

public class ProjectEuler_019 {
    public static void main(String[] args) {
        int result = 0; // 결과를 저장할 변수
        int dayOfWeek = 2; // 1901년 1월 1일이 화요일(2)이므로 초기값을 2로 설정합니다.

        // 1901년부터 2000년까지 각 년도와 월에 대한 반복문
        for (int year = 1901; year <= 2000; year++) {
            for (int month = 1; month <= 12; month++) {
                for (int day = 1; day <= getDays(year, month); day++) {
                    dayOfWeek++; // 요일을 다음으로 업데이트

                    // 매월 1일이 일요일(0)인 경우 결과를 증가시킴
                    if (day == 1 && dayOfWeek % 7 == 0) {
                        result++;
                    }
                }
            }
        }

        System.out.println("The number of Sundays fell on the first of the month during 20th century is " + result);
    }

    // 해당 월의 일수를 반환하는 메서드
    public static int getDays(int year, int month) {
        if (month == 2) {
            // 2월은 윤년 체크 후 일수 결정
            if (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) {
                return 29;
            } else {
                return 28;
            }
        } else if (month == 4 || month == 6 || month == 9 || month == 11) {
            return 30;
        } else {
            return 31;
        }
    }
}

 

 

20세기의 일요일 중 1일인 날을 찾기

 

C#에선 DateTime을 사용했던 것 같은데, Java에서 비슷한 네임스페이스가 뭔지 몰라서 그냥 계산을 했다.