题目大意:
求第n年第a个月有没有第b个星期c,有就输出日期,没有就输出none。
思路
要知道有没有第几个星期几,就从这年的这个月开始数星期几。数到对应的星期几计数器就加一。
所以数之前,要求出这个月的1月1号是星期几。
因为题目只有“1850年1月1号是星期2”这个信息。所以我们可以把这一年之前的日数加起来,再把这一年这个月之前的日数加起来,再求余就可以求得这个月第一天是星期几。
然后就在这个月第一天开始,求每一天是星期几,是题目要求的星期几就计数器加一,直到等于题目给的参数,说明这个月有第几个星期几,数完整个月还不够就none。这里注意:如果是闰年的2月,2月就是29。
某天是星期几 = (从1850/1/1开始到某天的总天数 + 1)% 7--------day = (totalday + 1) % 7
import java.util.Scanner;
public class 节日_new {
static int[] months = {31,28,31,30,31,30,31,31,30,31,30,31};
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int month = input.nextInt();
int week = input.nextInt();
int day = input.nextInt();
int startY = input.nextInt();
int endY = input.nextInt();
for (int i = startY; i <= endY; i++) {
//求1850/1/1-某年某月的总天数
int totalDays = 0;
for (int j = 1850; j < i; j++) {
totalDays += 365;
if (isLeapYear(j))
totalDays++;
}
//加这年的过完了的月
for (int j = 0; j < month - 1; j++) {
totalDays += months[j];
if (j == 1 && isLeapYear(i))
totalDays++;
}
//在要求的这个月里面一天天的遍历,是对应的星期几,count就加加,直到等于week
int n = isLeapYear(i) && month - 1 == 1 ?
months[month - 1] + 1 : months[month - 1];
int count = 0;
for (int j = 0; j < n; j++) {
totalDays++;
if (getWeekOfDay(totalDays) == day)
count++;
if (count == week) {
System.out.println(i + "/" + fillSingle(month) +
"/" + fillSingle(j + 1));
break;
}
}
if (count < week)
System.out.println("none");
}
}
static boolean isLeapYear(int year) {
return year % 400 == 0 || year % 4 == 0 && year % 100 != 0;
}
//给定从1850/1/1开始到某个日期的天数,
// 求这个日期是星期几,1-7代表星期一到日。
// 1850/1/1的tatalDays=1,
// 求出来刚刚好是2,星期二
static int getWeekOfDay(int n) {
return n % 7 + 1;
}
static String fillSingle(int num) {
if (num < 10)
return "0" + num;
return num + "";
}
}
python代码
months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
for i in range(y1, y2 + 1):
# 计算1850到这年之前一共过了多少天
totaldays = 0
for j in range(1850, i):
if (j % 4 == 0 and j % 100 != 0) or j % 400 == 0:
totaldays += 366
else:
totaldays += 365
# 计算这年1月1日到这个月1月1日一共多少天
for j in range(a - 1):
totaldays += months[j]
if j == 1 and ((i % 4 == 0 and i % 100 != 0) or i % 400 == 0):
totaldays += 1
# 这年这月1月1日的星期数,0是星期一
day = (totaldays + 1) % 7
count = 0
thismonth = months[a - 1]
if ((i % 4 == 0 and i % 100 != 0) or i % 400 == 0):
thismonth += 1
for j in range(thismonth):
if day == c - 1:
count += 1
if count == b:
month = '0' + str(a) if a < 10 else str(a)
d = '0' + str(j + 1) if j + 1 < 10 else str(j + 1)
print(str(i) + '/' + month + '/' + d)
break
day = (day + 1) % 7
else:
print('none')