计算一年中的第几天

思路

给你年、月、日三个整数,算出这一天是当年的第几天。思路很直接——把前面所有完整月份的天数加起来,再加上当月的天数就行。

唯一需要注意的就是闰年的判断。闰年 2 月有 29 天,平年只有 28 天。闰年的规则是:

  • 能被 4 整除不能被 100 整除,或者
  • 能被 400 整除

比如 2000 年是闰年(被 400 整除),1900 年不是闰年(被 100 整除但不被 400 整除),2024 年是闰年(被 4 整除不被 100 整除)。

做法

  1. 预存每个月的天数 {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
  2. 判断是否闰年。
  3. 累加第 1 个月到第 个月的天数,如果是闰年且经过了 2 月,额外加 1。
  4. 最后加上当月的天

注意本题有多组输入,要循环读到 EOF。

复杂度

  • 时间复杂度:,每组数据最多遍历 12 个月。
  • 空间复杂度:

代码

#include <iostream>
using namespace std;

int main() {
    int y, m, d;
    int days[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    while (cin >> y >> m >> d) {
        bool leap = (y % 4 == 0 && y % 100 != 0) || (y % 400 == 0);
        int ans = d;
        for (int i = 1; i < m; i++) {
            ans += days[i];
            if (i == 2 && leap) ans += 1;
        }
        cout << ans << endl;
    }
    return 0;
}
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int[] 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();
            boolean leap = (y % 4 == 0 && y % 100 != 0) || (y % 400 == 0);
            int ans = d;
            for (int i = 1; i < m; i++) {
                ans += days[i];
                if (i == 2 && leap) ans += 1;
            }
            System.out.println(ans);
        }
    }
}
import sys

days = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
for line in sys.stdin:
    parts = line.split()
    if len(parts) < 3:
        continue
    y, m, d = int(parts[0]), int(parts[1]), int(parts[2])
    leap = (y % 4 == 0 and y % 100 != 0) or (y % 400 == 0)
    ans = d
    for i in range(1, m):
        ans += days[i]
        if i == 2 and leap:
            ans += 1
    print(ans)
const readline = require('readline');
const rl = readline.createInterface({ input: process.stdin });
const lines = [];
rl.on('line', line => lines.push(line.trim()));
rl.on('close', () => {
    const days = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    const res = [];
    for (const line of lines) {
        const parts = line.split(/\s+/);
        if (parts.length < 3) continue;
        const y = parseInt(parts[0]), m = parseInt(parts[1]), d = parseInt(parts[2]);
        const leap = (y % 4 === 0 && y % 100 !== 0) || (y % 400 === 0);
        let ans = d;
        for (let i = 1; i < m; i++) {
            ans += days[i];
            if (i === 2 && leap) ans += 1;
        }
        res.push(ans);
    }
    console.log(res.join('\n'));
});