Project Eluer - 19

来源:互联网 发布:杨颖同款秀禾服淘宝 编辑:程序博客网 时间:2024/04/29 18:05

Counting Sundays

Problem 19


You are given the following information, but you may prefer to do some research for yourself.

  • 1 Jan 1900 was a Monday.
  • Thirty days has September,
    April, June and November.
    All the rest have thirty-one,
    Saving February alone,
    Which has twenty-eight, rain or shine.
    And on leap years, twenty-nine.
  • A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.

How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?


翻译:下面是一些信息:

1900年1月1日是星期一,

有30天的月份有:4,6,9,11月,

有31天的月份有:1,3,5,7,8,10,12。

2月闰年有29天,平年28天。判断条件是: isLeap = (year%4==0 && year%100!=0) || (year%400==0)

请计算从 1901年1月1日到2000年12月31日,每个月的第一天是星期天的天数一共有多少?


解决思路:从1900年1月1日开始,我们设置它为相对的第1天,以后每过一天依次递加,如果这个值 mod 7 等于0,那就说明是星期天。那么我们只需要得到每个月第一天是相对的第几天,然后mod 7就可以得到是否是星期天。主要是需要区别闰年和平年的2月不确定有多少天,所以在加月份天数的时候需要判断是闰年还是平年。

代码:

package projectEuler;public class Problem19 {static int[][] monthDays;public static void main(String[] args) {int result = 0;monthDays = new int[][] {{ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },{ 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 } };int relativeDayth = 1;for (int year = 1900; year <= 2000; year++) {int isLeap = isLeap(year);for (int month = 0; month < 12; month++) {if (0 == relativeDayth % 7 && year > 1900) {result++;}relativeDayth += monthDays[isLeap][month];}}System.out.println("result:"+result);}private static int isLeap(int year) {if ((0 != year % 100 && 0 == year % 4) || (year % 400 == 0)) {return 1;} else {return 0;}}}

这里需要注意,题目要求是1901年1月1日开始,所以还需要加判断 year>1900。

代码很简单,看一下就懂了。

结果是:171



0 0
原创粉丝点击