Problem 19: How many Sundays fell on the first of the month during the twentieth century?
public class Main{
private static boolean isLeap(int year){
if( year % 400 == 0 ) return true;
if( year % 4 == 0 && year % 100 != 0 ) return true;
return false;
}
public static void main(String[] args) {
int year = 1901; int year_end = 2000;
int find_day = 6; //Find Sunday (0 is Monday)
int[] nonleap = {31,28,31,30,31,30,31,31,30,31,30,31};
int[] leap = {31,29,31,30,31,30,31,31,30,31,30,31};
int counter = 0;
/*int day = 0; which is Jan 1 1900, Monday
setup the date - (the day before "var year") */
int setup_year = 1900;
int day = 0;
while(setup_year < year){
int[] months = isLeap(year) ? leap : nonleap;
for(int month : months){
day += month;
}
setup_year ++;
}
while(year <= year_end){
int[] months = isLeap(year) ? leap : nonleap;
for(int month : months){
if((day+1)% 7 == find_day) counter ++;//Find first "day" of each month
day += month;
}
year ++;
}
System.out.println(counter);
}
}