题目链接
题目描述
输入年、月、日,计算该天是本年的第几天。
输入描述
包括三个整数年 (
)、月
(
)、日
(
)。
输入可能有多组测试数据。
输出描述
对于每一组测试数据,输出一个整数,代表输入的年、月、日对应本年的第几天。
样例
输入
1990 9 20
2000 5 1
输出
263
122
解题思路
本题的核心是累加指定日期之前所有月份的总天数,再加上当月的天数。唯一的难点在于判断闰年,因为闰年的2月份会多一天。
1. 闰年判断
一个年份 是闰年,需要满足以下两个条件之一:
能被4整除,但不能被100整除。
能被400整除。
2. 计算方法
我们可以预先定义一个数组,存储平年时每个月的天数,例如 。
(第0位留空,方便按月份直接索引)。
算法步骤如下:
- 对于每组输入的
:
- 初始化总天数
为 0。
- 遍历从1月到
月,将每个月的天数累加到
中。
- 将当月的天数
加到
。
- 判断年份
是否为闰年,并且月份
是否大于2。如果两个条件都满足,说明计算结果需要包含闰年多出来的那一天(2月29日),因此将
加 1。
- 输出最终的
。
由于题目可能包含多组测试数据,代码需要在一个循环中处理,直到没有新的输入为止。
代码
#include <iostream>
#include <vector>
using namespace std;
// 判断是否为闰年
bool isLeap(int year) {
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
int main() {
int y, m, d;
int month_days[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
while (cin >> y >> m >> d) {
int total_days = 0;
// 累加前 m-1 个月的天数
for (int i = 1; i < m; ++i) {
total_days += month_days[i];
}
// 加上当月天数
total_days += d;
// 如果是闰年且月份大于2,额外加一天
if (isLeap(y) && m > 2) {
total_days++;
}
cout << total_days << '\n';
}
return 0;
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] month_days = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
while (sc.hasNextInt()) {
int y = sc.nextInt();
int m = sc.nextInt();
int d = sc.nextInt();
int total_days = 0;
// 累加前 m-1 个月的天数
for (int i = 1; i < m; i++) {
total_days += month_days[i];
}
// 加上当月天数
total_days += d;
// 如果是闰年且月份大于2,额外加一天
if (isLeap(y) && m > 2) {
total_days++;
}
System.out.println(total_days);
}
}
// 判断是否为闰年
public static boolean isLeap(int year) {
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
}
# -*- coding: utf-8 -*-
import sys
def is_leap(year):
# 判断是否为闰年
return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
month_days = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
for line in sys.stdin:
y, m, d = map(int, line.split())
total_days = 0
# 累加前 m-1 个月的天数
for i in range(1, m):
total_days += month_days[i]
# 加上当月天数
total_days += d
# 如果是闰年且月份大于2,额外加一天
if is_leap(y) and m > 2:
total_days += 1
print(total_days)
算法及复杂度
- 算法:模拟
- 时间复杂度:对于每组测试数据,我们执行一次月数循环(最多12次)和一次闰年判断,这些都是常数时间操作。因此,单次查询的时间复杂度为
。如果总共有
组数据,则总时间复杂度为
。
- 空间复杂度:我们只使用了一个固定大小的数组来存储每月天数,因此空间复杂度为
。