給予以下信息,但您可能更願意爲自己做一些研究。Java中的項目Euler#19(off by 1)
1900年1月1日是星期一。 九月有三十天, 四月,六月和十一月。 其餘全部有31個, 單獨保存2月, 其中有二十八個,有雨還是有光。 閏年,二十九歲。 閏年發生在任何一年被4整除,但不是一個世紀,除非它可以被400整除。 20世紀(1901年1月1日至2000年12月31日)這個月的第一個月有多少個星期日下降?
我一直在得到172,答案是171.我不確定可能是什麼問題,我已經嘗試了一切,我一直得到172.感謝您的幫助。
public static void main(String args[]){
int year=1901;
boolean isLeapYear=false;
int totalSundays=0;
int currentDay=1;//Starts on a Monday
while(year<=2000){
isLeapYear=false;
if((year%4)==0){
if((year%100)==0 && (year%400)==0){
isLeapYear=true;
} else if((year%100)==0 && (year%400)!=0){
isLeapYear=false;
} else {
isLeapYear=true;
}
}
System.out.println("The Year Is: "+year);
System.out.println("*******************************");
for(int month=1;month<=12;month++){
System.out.println("The Month is: "+month+" currentDay is : "+currentDay);
if(currentDay==7){
totalSundays++;
}
if(month==1 || month==3 || month==5 || month==7 || month==8 || month==10 || month==12){
//January,March,May,July,August,October,December
currentDay+=3;
} else if(month==4 || month==6 || month==9 || month==11){
//April,June,September,November
currentDay+=2;
} else if(month==2 && isLeapYear){
//February has 29 days in a Leap Year
currentDay+=1;
}
if(currentDay>7){
currentDay=currentDay-7;
}
System.out.println("Updated Current Day Is : "+currentDay);
}
System.out.println("*******************************");
year++;
}
System.out.println("The total number of Sundays that fell in the first of the month is: "+totalSundays);
}
僅供參考,這將是一個更容易爲你/我們遵循和維護,如果你消除了魔術數字並使用了最終的int' – MartyE 2012-08-15 02:12:41