1啄踊、題目描述
從1900年1月1日(星期一)忧设,開(kāi)始經(jīng)過(guò)的n年當(dāng)中,沒(méi)個(gè)月的13號(hào)這一天是星期一颠通,星期二址晕,星期三...星期日的次數(shù)分別是多少?
2顿锰、解決代碼
import java.util.Scanner;
public class Main2
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
while (in.hasNextInt())
{
int years = in.nextInt();
int[] times = getTimes(years);
for (int i = 1; i <= 6; i++) {
System.out.print(times[i] + " ");
}
System.out.print(times[0] + " ");
}
}
private static int[] getTimes(int yesrs)
{
//下標(biāo)0-6分別表示星期日到星期六谨垃,數(shù)值表示13在星期幾出現(xiàn)幾次
int[] times = new int[7];
int week = 6; //1990年第一個(gè)13號(hào)出現(xiàn)在星期六
for (int i = 1900; i < 1900 + yesrs; ++i)
{
for (int m = 1; m <= 12; ++m)
{
times[week % 7]++;
week += getMonthDays(i, m);
}
}
return times;
}
private static int getMonthDays(int year, int month)
{
boolean isLeapYear = false;
//判斷是否為閏年
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))
isLeapYear = true;
if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12)
return 31;
else if (month == 2)
{
if (isLeapYear)
return 29;
else return 28;
}
else
return 30;
}
public static boolean tag(int year) {
if (year % 400 == 0)
return true;
if (year % 100 == 0)
return false;
if ((year & 3) == 0)
return true;
else
return false;
}
}
參考文章:https://blog.csdn.net/qq_26498709/article/details/78323868