解题思路

  1. 题目要求:

    • 根据输入的日期,计算是这一年的第几天
    • 输入格式为:年 月 日
    • 输入年份为4位数且大于等于1
    • 输入月份为1-12
    • 输入日期为1-31
  2. 解题方法:

    • 计算从1月1日到输入日期的天数
    • 需要考虑闰年的情况
    • 累加每个月的天数

代码

def is_leap_year(year):
    return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)

def calculate_days(year, month, day):
    # 每个月的天数(非闰年)
    days_in_month = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    
    # 如果是闰年,2月有29天
    if is_leap_year(year):
        days_in_month[2] = 29
    
    # 计算总天数
    total_days = day
    for i in range(1, month):
        total_days += days_in_month[i]
    
    return total_days

while True:
    try:
        year, month, day = map(int, input().split())
        print(calculate_days(year, month, day))
    except:
        break
import java.util.*;

public class Main {
    public static boolean isLeapYear(int year) {
        return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
    }
    
    public static int calculateDays(int year, int month, int day) {
        // 每个月的天数(非闰年)
        int[] daysInMonth = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
        
        // 如果是闰年,2月有29天
        if (isLeapYear(year)) {
            daysInMonth[2] = 29;
        }
        
        // 计算总天数
        int totalDays = day;
        for (int i = 1; i < month; i++) {
            totalDays += daysInMonth[i];
        }
        
        return totalDays;
    }
    
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            int year = sc.nextInt();
            int month = sc.nextInt();
            int day = sc.nextInt();
            System.out.println(calculateDays(year, month, day));
        }
    }
}
#include <iostream>
using namespace std;

bool isLeapYear(int year) {
    return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
}

int calculateDays(int year, int month, int day) {
    // 每个月的天数(非闰年)
    int daysInMonth[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    
    // 如果是闰年,2月有29天
    if (isLeapYear(year)) {
        daysInMonth[2] = 29;
    }
    
    // 计算总天数
    int totalDays = day;
    for (int i = 1; i < month; i++) {
        totalDays += daysInMonth[i];
    }
    
    return totalDays;
}

int main() {
    int year, month, day;
    while (cin >> year >> month >> day) {
        cout << calculateDays(year, month, day) << endl;
    }
    return 0;
}

算法分析

  • 算法:直接计算
  • 时间复杂度:,其中 为月份数
  • 空间复杂度:,只需要常数级别的额外空间