Coding Exercise 13: Number Of Days in Month

2021. 3. 3. 15:32Java programming

Write a method isLeapYearwith a parameter of type int named yaer.

 

The parameter needs to be greater than or equal to 1 and less than or equal to 9999.

 

If the parameter is not in that range return false.

 

Otherwise, if it's in the valid range, calculate if the year is a leap year and return true if it is, otherwise, return false.

 

A year is a leap year if it's divdisible by 4 but not by 100, or it's divisible by 400.

 

public class NumberOfDaysInMonth {
    public static boolean isLeapYear(int year) {
        if (year >= 1 && year <= 9999) {
            if (year % 4 == 0) {
                if (year % 100 == 0) {
                    if (year % 400 == 0) {
                        return true;
                    } else {
                        return false;
                    }
                } else {
                    return true;
                }

            } else {
                return false;
            }


        }
        return false;
    }


    public static int getDaysInMonth(int month, int year) {
        if (month < 1 || month > 12 || year < 1 || year > 9999) {
            return -1;
        }
        switch (month) {
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12:
                return 31;

            case 4:
            case 6:
            case 9:
            case 11:
                return 30;

            case 2:
                if (isLeapYear(year)) {
                    return 29;
                } else {
                    return 28;
                } default:
                return -1;
            }
        }
    }

1부터 9999년도까지 중 문제에서 요구하는 leap year를 먼저 찾아야 한다.

leap year는 4로 나누어 떨어지지거나 400으로도 나누어떨어지면 된다.

하지만 100으로 나누어 떨어지면 안된다.

leap year를 구한 후에 31일까지 있는 달과 30일까지 있는 달을 switch를 통해 값을 return한다 (2월을 제외하고).

2월은 lear year일 경우엔 29일수를, leap year가 아닐 경우에는 28일수를 리턴한다.

'Java programming' 카테고리의 다른 글

Coding Exercise 15: Number Palindrome  (0) 2021.03.11
Coding Exercise 14: Sum Odd  (0) 2021.03.06
Coding Exercise 12: Number in Word  (0) 2021.03.03
Coding Exercise 11: Playing Cat  (0) 2021.03.02
Coding Exercise 10: Equality Printer  (0) 2021.03.01