Day Number in the Year
Problem
Read a valid date as three integers: day, month, year. Print the day number in the year (1 January is day 1). Leap years have 366 days.
Constraints
- The date is valid
- 1 <= year <= 9999
Examples
Input
1 3 2024
Output
61
Solutions
Adding up month lengths is simple and needs no date library. Java also has LocalDate.getDayOfYear(), which does the same.
/*
* Problem : Process a date.
* Input : One line of text.
* Output : The day number.
* Approach: day month year.
* 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(String s) {
// Step 1: Read day, month and year from the line.
String[] part = s.trim().split("\\s+");
int day = Integer.parseInt(part[0]);
int month = Integer.parseInt(part[1]);
int year = Integer.parseInt(part[2]);
// Step 2: February has 29 days in a leap year.
boolean leap = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
int[] days = {31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
// Step 3: Add the days of all full months before this month, then add the day of the month.
int total = day;
for (int i = 0; i < month - 1; i++) {
total += days[i];
}
return total;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String s = scanner.hasNextLine() ? scanner.nextLine() : "";
System.out.println(solve(s));
}
}
Hints (1)
- Why is the day number of 31 December 366 in a leap year?