项目Euler#19 in Java

时间:2012-07-02 10:53:41

标签: java project

您将获得以下信息,但您可能更愿意为自己做一些研究。

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.

在二十世纪的第一个月(1901年1月1日至2000年12月31日),有多少个星期日下降?

解决方案:

我的以下逻辑给了我173个星期天,而有171个星期天!!额外的2天来自哪里?

public static void main(String args[]) {

    Date startDate = new Date(1901, Calendar.JANUARY, 01);
    Date endDate = new Date(2000, Calendar.DECEMBER, 31);

    checkSundays(startDate, endDate);
}

private static void checkSundays(Date start, Date end) {
    int dayNum;

    Calendar startDate = Calendar.getInstance();
    startDate.setTime(start);
    System.out.println(startDate.getTime());

    Calendar endDate = Calendar.getInstance();
    endDate.setTime(end);
    System.out.println(endDate.getTime());
    int count = 0;

    while (startDate.before(endDate)) {
        for (int i = 1; i < 13; i++) {
            dayNum = startDate.get(Calendar.DAY_OF_WEEK);
            if (dayNum == 1) {
                count++;
            }

            System.out.println(startDate.getTime());
            startDate.add(Calendar.MONTH, 1);

        }
            System.out.println("Count " + count);

    }
}

2 个答案:

答案 0 :(得分:3)

以下代码使用Date

的弃用构造函数
Date startDate = new Date(1901, Calendar.JANUARY, 01);
System.out.println(startDate);

哪个不合适,打印

Thu Jan 01 00:00:00 IST 3801

因此,请使用Calendar构建Date

    Calendar startDateCal = createDateInstance(0,1901,1)

    Calendar endDateCal = createDateInstance(11,2000,13)

和工厂方法

public static Date createDateInstance(int month, int year, int date){
  Calendar cal= Calendar.getInstance();
  cal.set(Calendar.YEAR, year);
  cal.set(Calendar.MONTH, month);
  cal.set(Calendar.DATE, date);

  return cal.getTime();

}

请参阅your working code

答案 1 :(得分:0)

您可以使用概率并仅使用计算器执行此操作。

一个世纪以来有100年,而且每年都有12个月的第一天。将它除以7即可得到答案。

价格便宜,但有效。