2016蓝桥杯假期任务之《日期计算》

来源:互联网 发布:配电网设计软件 编辑:程序博客网 时间:2024/05/22 17:29

问题描述
  已知2011年11月11日是星期五,问YYYY年MM月DD日是星期几?注意考虑闰年的情况。尤其是逢百年不闰,逢400年闰的情况。
输入格式
  输入只有一行
  YYYY MM DD
输出格式
  输出只有一行
  W
数据规模和约定
  1599 <= YYYY <= 2999
  1 <= MM <= 12
  1 <= DD <= 31,且确保测试样例中YYYY年MM月DD日是一个合理日期
  1 <= W <= 7,分别代表周一到周日
样例输入
2011 11 11
样例输出
5

代码如下:

import java.util.Scanner;public class Main {static int a[][] = { { 0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },{ 0, 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 y = input.nextInt();int m = input.nextInt();int d = input.nextInt();int week = Day(y, m, d) - Day(2011, 11, 11);if (week > 0)System.out.println((4 + week % 7) % 7 + 1);else {for (int i = 1; i <= 7; ++i)if ((i - 1 + -week % 7) % 7 + 1 == 5) {System.out.println(i);break;}}}public static boolean isRun(int year) {if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0)return true;return false;}public static int Day(int y, int m, int d) {int ans = 0;for (int i = 1; i < y; ++i)ans += calDay(i);int index = 0;if (!isRun(y))index = 1;for (int i = 1; i < m; ++i)ans += a[index][i];ans += d;return ans;}public static int calDay(int year) {int index = 0;if (!isRun(year))index = 1;int tot = 0;for (int i = 1; i <= 12; ++i)tot += a[index][i];return tot;}}
运行结果:

2011 11 11
5

1 0