CCF-201503-3-節日(Java-100)
阿新 • • 發佈:2018-12-01
思路
要求每年第幾個月第幾個星期有沒有星期幾,有就輸出日期,沒有就輸出none。要知道有沒有第幾個星期幾,就從那個月開始數星期幾。數到對應的星期幾計數器就加一。
數之前,先把這一年年之前的日數加起來,再把這一年這個月之前的日數加起來。然後就在這個月1月1號開始,求每一天是星期幾,是題目要求的星期幾就計數器加一,直到等於題目給的引數,說明這個月有第幾個星期幾,數完整個月還不夠就none。
求某天是星期幾的方法要從1850/1/1開始到某個日期的總天數除於7加1。
節日這道題,難度一般般,主要還是看細心,題目其實很快寫好,就是總是差一天,後來仔細想想原來是求某天是星期幾的時候漏了1850年1月1號,因為我是總天數除於7嘛。然後我求總天數的方法是從1850/1/1開始加年加月加日。所以1850/1/1總天數為1,求出來的星期數是2,就剛剛好了。
import java.util.Scanner;
public class 節日_new {
static int[] months = {31,28,31,30,31,30,31,31,30,31,30,31};
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int month = input.nextInt();
int week = input.nextInt();
int day = input.nextInt();
int startY = input.nextInt();
int endY = input.nextInt();
for (int i = startY; i <= endY; i++) {
//求1850/1/1-某年某月的總天數
int totalDays = 0;
for (int j = 1850; j < i; j++) {
totalDays += 365;
if (isLeapYear(j))
totalDays++;
}
//加這年的過完了的月
for (int j = 0; j < month - 1; j++) {
totalDays += months[j];
if (j == 1 && isLeapYear(i))
totalDays++;
}
//在要求的這個月裡面一天天的遍歷,是對應的星期幾,count就加加,直到等於week
int n = isLeapYear(i) && month - 1 == 1 ?
months[month - 1] + 1 : months[month - 1];
int count = 0;
for (int j = 0; j < n; j++) {
totalDays++;
if (getWeekOfDay(totalDays) == day)
count++;
if (count == week) {
System.out.println(i + "/" + fillSingle(month) +
"/" + fillSingle(j + 1));
break;
}
}
if (count < week)
System.out.println("none");
}
}
static boolean isLeapYear(int year) {
return year % 400 == 0 || year % 4 == 0 && year % 100 != 0;
}
//給定從1850/1/1開始到某個日期的天數,
// 求這個日期是星期幾,1-7代表星期一到日。
// 1850/1/1的tatalDays=1,
// 求出來剛剛好是2,星期二
static int getWeekOfDay(int n) {
return n % 7 + 1;
}
static String fillSingle(int num) {
if (num < 10)
return "0" + num;
return num + "";
}
}