http://projecteuler.net/problem=19
You are given the following information, but you may prefer to do some research for yourself.
How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?
20世纪(1901年1月1日到2000年12月31日)一共有多少个星期日落在了当月的第一天?
public class TwentiethCentury { public static void main(String args[]){ int all=0; for(int i=1901;i<=2000;i++){ all+=everyMonth(i, i); } // System.out.println(everyMonth(1901, 1901)); System.out.println(all); } public static boolean isLeap(int year){ if((year%4==0&&year%100!=0)||(year%400==0)) return true; return false; } public static int everyMonth(int year,int leave){ int sum=0; int j=0; int num=leaveNum(leave); for(int i=1;i<=12;i++){ if(i==1){ sum=num+1; if(isSunday(sum)){ j++; System.out.println("year="+year+",month="+i+",sum="+sum); } }else if(i==2){ sum+=31; if(isSunday(sum)){ j++; System.out.println("year="+year+",month="+i+",sum="+sum); } }else if(i==3){ if(isLeap(year)){ sum+=29; if(isSunday(sum)){ j++; System.out.println("year="+year+",month="+i+",sum="+sum); } }else{ sum+=28; if(isSunday(sum)){ j++; System.out.println("year="+year+",month="+i+",sum="+sum); } } }else if(i==4){ sum+=31; if(isSunday(sum)){ j++; System.out.println("year="+year+",month="+i+",sum="+sum); } }else if(i==5){ sum+=30; if(isSunday(sum)){ j++; System.out.println("year="+year+",month="+i+",sum="+sum); } }else if(i==6){ sum+=31; if(isSunday(sum)){ j++; System.out.println("year="+year+",month="+i+",sum="+sum); } }else if(i==7){ sum+=30; if(isSunday(sum)){ j++; System.out.println("year="+year+",month="+i+",sum="+sum); } }else if(i==8){ sum+=31; if(isSunday(sum)){ j++; System.out.println("year="+year+",month="+i+",sum="+sum); } }else if(i==9){ sum+=31; if(isSunday(sum)){ j++; System.out.println("year="+year+",month="+i+",sum="+sum); } }else if(i==10){ sum+=30; if(isSunday(sum)){ j++; System.out.println("year="+year+",month="+i+",sum="+sum); } }else if(i==11){ sum+=31; if(isSunday(sum)){ j++; System.out.println("year="+year+",month="+i+",sum="+sum); } }else if(i==12){ sum+=30; if(isSunday(sum)){ j++; System.out.println("year="+year+",month="+i+",sum="+sum); } } } return j; } public static boolean isSunday(int num){ if(num%7==0) return true; return false; } public static int leaveNum(int year){ int sum=0; if(year==1901){ sum=0; System.out.println("leaveNum="+sum); }else if((year-1901)%4==0){ sum+=(year-1901)/4*(365*3+366); System.out.println("leaveNum="+sum); }else if((year-1901)%4==1){ sum+=(year-1901)/4*(365*3+366)+365; System.out.println("leaveNum="+sum); }else if((year-1901)%4==2){ sum+=(year-1901)/4*(365*3+366)+365*2; System.out.println("leaveNum="+sum); }else if((year-1901)%4==3){ sum+=(year-1901)/4*(365*3+366)+365*2+366; System.out.println("leaveNum="+sum); } return sum%7; } }
Answer:
|
171 |