Days in a Month (switch with yield)
Problem
Read a month number (1 to 12) and a year. Print how many days that month has. February has 29 days in a leap year, else 28.
Constraints
- 1 <= month <= 12
- 1 <= year <= 9999
Examples
Input
2 2024
Output
29
Input
4 2021
Output
30
Solutions
Plain if statements work in every Java version. They are fine, but the rule for each month is spread over several branches.
/*
* Problem : Find the number of days.
* Input : Month and year.
* Output : The number of days.
* Approach: If statements.
* Time : O(1)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static int solve(long a, long b) {
// Step 1: February depends on the year. Other months have a fixed length.
int month = (int) a;
long year = b;
if (month == 2) {
boolean leap = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
return leap ? 29 : 28;
}
// Step 2: April, June, September and November have 30 days. All other months have 31.
if (month == 4 || month == 6 || month == 9 || month == 11) {
return 30;
}
return 31;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
long a = scanner.nextLong();
long b = scanner.nextLong();
System.out.println(solve(a, b));
}
}
Hints (1)
- Which months have 30 days?