1.package com.shui.mu.yao.io.algorithm;
2.
3.import java.util.Calendar;
4.
5./**
6. *
7. * @author shuimuqinghua77 @date 2011-12-9上午09:58:49
8. */
9.public class Problem19 {
10.
11. public static void main(String[] args) {
12. int count = oneDayTotal(1901,2000,/** 1901年1月1日是周二 **/Calendar.TUESDAY,/**期望获取每个月第一天周日的总数**/Calendar.SUNDAY);
13. System.out.println(count);
14.
15. }
16./**
17. *
18. * @param startYear开始年份
19. * @param endYear结束年份
20. * @param startWeek开始年份1月1日是星期几
21. * @param wantWeek 期望每月第一天为星期几
22. * @return
23. */
24. private static int oneDayTotal( int startYear,int endYear ,int startWeek,int wantWeek) {
25.
26. int week = startWeek;
27. int count = 0;/**记录下个月第一天是周日的总数**/
28. int week_size = 7;/**一周7天 **/
29. /***判断 startYear年1月1日是不是周日**/
30. if (week == wantWeek)
31. count++;
32. for (int year = startYear; year <= endYear; year++) {
33. for (int month = 1; month <= 12; month++) {
34. int days = getDays(month, year);
35. week = (week + days % week_size) % week_size;
36. if (week == wantWeek)
37. count++;
38. }
39. }
40. /***判断 endYear年1月1日是不是周日,是的话减去**/
41. if (week == wantWeek)
42. count--;
43. return count;
44. }
45.
46. private static boolean isLeapYear(int year) {
47. if (year % 4 == 0 && year % 100 > 0)
48. /** 不是世纪,但可以被4整除,为闰年 **/
49. return true;
50. else if (year % 400 == 0)
51. /** 世纪,但可以被400整除,为闰年 **/
52. return true;
53. else
54. return false;
55.
56. }
57.
58. private static int getDays(int month, int year) {
59. if (month == 2) {
60. if (isLeapYear(year))
61. return 29;
62. else
63. return 28;
64. }
65. if (month == 4 || month == 6 || month == 9 || month == 11)
66. return 30;
67. else
68. return 31;
69. }
70.}