目录
1 问题描述
2 解决方案
1 问题描述
问题描述
已知2011年11月11日是星期五,问YYYY年MM月DD日是星期几?注意考虑闰年的情况。尤其是逢百年不闰,逢400年闰的情况。
输入格式
输入只有一行
YYYY MM DD
输出格式
输出只有一行
W
数据规模和约定
1599 <= YYYY <= 2999
1 <= MM <= 12
1 <= DD <= 31,且确保测试样例中YYYY年MM月DD日是一个合理日期
1 <= W <= 7,分别代表周一到周日
样例输入
2011 11 11
样例输出
5
2 解决方案
具体代码如下:
import java.util.Scanner; public class Main { public boolean judgeYear(int year) { if(year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) return true; //此时为闰年 return false; //此时为平年 } public int getMonth(int year, int month) { //获取月份天数 if(month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) return 31; if(month == 4 || month == 6 || month == 9 || month == 11) return 30; if(judgeYear(year) && month == 2) return 29; if(!judgeYear(year) && month == 2) return 28; return 0; } public void getResult(String date) { String[] temp = date.split(" "); int year = Integer.valueOf(temp[0]); int month = Integer.valueOf(temp[1]); int day = Integer.valueOf(temp[2]); int countDay = 0; int result = 0; //最终结果 if(year > 2011) { for(int i = 1;i < month;i++) countDay += getMonth(year, i); countDay += day; for(int i = year - 1;i > 2011;i--) { //跳出循环时i = 2011 if(judgeYear(i)) countDay += 366; else countDay += 365; } countDay = countDay + 19 + 31; //加上2011年11月份剩余天数和12月份31天 result = 5 + countDay % 7; if(result != 7) result = result % 7; } else if(year < 2011){ countDay = countDay + (getMonth(year, month) - day); month++; for(;month <= 12;month++) countDay += getMonth(year, month); for(int i = year + 1;i < 2011;i++) { //跳出循环时i = 2011 if(judgeYear(i)) countDay += 366; else countDay += 365; } for(int i = 1;i <= 10;i++) countDay += getMonth(2011, i); countDay += 11; result = 5 - countDay % 7; if(result == 0) result = 7; else if(result == -1) result = 6; else if(result == -2) result = 5; } else if(year == 2011) { if(month > 11) { countDay = countDay + 19 + day; } else if(month == 11) { if(day >= 11) { countDay = day - 11; } else if(day < 11) countDay = 11 - day; } else if(month < 11) { countDay += getMonth(2011, month) - day; int i = month + 1; for(;i <= 10;i++) countDay += getMonth(2011,i); countDay += 11; } if(month >= 11 && day >= 11) { result = 5 + countDay % 7; if(result != 7) result = result % 7; } else { result = 5 - countDay % 7; if(result == 0) result = 7; else if(result == -1) result = 6; else if(result == -2) result = 5; } } System.out.println(result); } public static void main(String[] args) { Main test = new Main(); Scanner in = new Scanner(System.in); String date = in.nextLine(); test.getResult(date); } }
时间: 2024-10-05 23:52:47