2012-07-02 4 views
1

다음과 같은 정보가 제공되지만 직접 조사해 보는 것이 좋습니다.프로젝트 오일러 # 19 (Java)

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. 

20 세기 (1901 년 1 월 1 일부터 2000 년 12 월 31 일)까지 매월 1 일에 몇 일요일이 감소 했습니까?

솔루션 : 171 일이있는 반면

내 다음과 같은 논리가, 나에게 173 일을 제공합니다! 여분의 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); 

    } 
} 
+0

'Date'생성자가 사용되지 않습니다. – trashgod

답변

3

당신의 다음 코드는 적절하지 않다 Date

Date startDate = new Date(1901, Calendar.JANUARY, 01); 
System.out.println(startDate); 

의 사용되지 않는 생성자를 사용하여, 그것은

Thu Jan 01 00:00:00 IST 3801 

그래서 Date를 구성하는 Calendar를 사용하여 인쇄

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

'Calendar' 클래스는 0에서 11까지의 달을 사용하기 때문에 나에게는 틀린 것처럼 보입니다. 비록 내가 볼 수없는 정당화가 있다면, 그것을 자유롭게 제공하십시오. –

+0

@Anthony 예, 실수였습니다. 수정되었습니다. –

+0

+1 월 상수를 더 쉽게 읽을 수 있습니까? 'set (Calendar.MONTH, Calendar.JANUARY)'? – trashgod

0

참조하십시오.

100 년이라는 세월이 지났으며 매년 매년 12 일이됩니다. 7로 나누면 답을 얻을 수 있습니다.

저렴하지만 작동합니다.

+0

이것은 실제로 작동하지 않습니다 ... 대답은 세기와 시작/끝 날짜가 무엇인지에 달려 있습니다. – jiaweizhang