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
- Project Eluer - 19
- Project Eluer - Problem 11
- Project Eluer - 14
- Project Eluer - 15
- Project Eluer - 16
- Project Eluer - 17
- Project Eluer - 18
- Project Eluer - 20
- Project Eluer - 21
- Project Eluer - 22
- Project Eluer - 23
- 有限差分法Eluer算法(求解常微分方程)
- Project Euler problem 19
- Project Euler 19
- project euler 19
- project euler 19
- project
- project
- 【原创】一些正则表达式
- Binary Tree Level Order Traversal II
- 工业水处理:威立雅锅炉给水处理技术解析
- 仙境传说OX答题器
- mysql遇到error1045或2003
- Project Eluer - 19
- 使用jdbc驱动连接oracle数据库
- 全排列
- 详解JVM的内存管理机制
- 关于linux SCSI 子系统
- sys.argv[]用法
- stack,deque,queue对比
- 序列化的一些注意事项及建议
- C++11:类型推导和追踪函数返回类型decltype