解题思路

这是一个日期计算问题。需要考虑闰年和每个月的天数,将给定日期转换为该年的第几天。

关键点:

  1. 判断闰年
  2. 计算每个月的天数
  3. 处理多组输入

算法步骤:

  1. 判断是否为闰年
  2. 累加前几个月的天数
  3. 加上当月的天数

代码

#include <bits/stdc++.h>
using namespace std;

class Solution {
private:
    // 每个月的天数(非闰年)
    const int days[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    
    bool isLeapYear(int year) {
        return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
    }
    
public:
    int solve(int year, int month, int day) {
        int result = day;
        
        // 累加前几个月的天数
        for (int i = 0; i < month - 1; i++) {
            result += days[i];
        }
        
        // 如果是闰年且已经过了2月,加1天
        if (isLeapYear(year) && month > 2) {
            result++;
        }
        
        return result;
    }
};

int main() {
    int year, month, day;
    Solution solution;
    
    while (cin >> year >> month >> day) {
        cout << solution.solve(year, month, day) << endl;
    }
    
    return 0;
}
import java.util.*;

public class Main {
    static class Solution {
        // 每个月的天数(非闰年)
        private final int[] days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
        
        private boolean isLeapYear(int year) {
            return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
        }
        
        public int solve(int year, int month, int day) {
            int result = day;
            
            // 累加前几个月的天数
            for (int i = 0; i < month - 1; i++) {
                result += days[i];
            }
            
            // 如果是闰年且已经过了2月,加1天
            if (isLeapYear(year) && month > 2) {
                result++;
            }
            
            return result;
        }
    }
    
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        Solution solution = new Solution();
        
        while (sc.hasNext()) {
            int year = sc.nextInt();
            int month = sc.nextInt();
            int day = sc.nextInt();
            
            System.out.println(solution.solve(year, month, day));
        }
        
        sc.close();
    }
}
class Solution:
    def __init__(self):
        # 每个月的天数(非闰年)
        self.days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    
    def is_leap_year(self, year: int) -> bool:
        return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
    
    def solve(self, year: int, month: int, day: int) -> int:
        result = day
        
        # 累加前几个月的天数
        for i in range(month - 1):
            result += self.days[i]
        
        # 如果是闰年且已经过了2月,加1天
        if self.is_leap_year(year) and month > 2:
            result += 1
        
        return result

# 处理多组输入
solution = Solution()
while True:
    try:
        year, month, day = map(int, input().split())
        print(solution.solve(year, month, day))
    except EOFError:
        break

算法及复杂度

  • 算法:直接计算
  • 时间复杂度:,只需要遍历月份数组
  • 空间复杂度:,只需要存储月份天数数组