计算日期之差(包含日期头尾)

题目
输入:YYYY MM DD
计算到20211024程序员节的这一天的
Day数

代码:
JAVA版本:

import java.util.Scanner;

public class App {
    static boolean IsLeapYear(int y) {
        return (y % 4 == 0 || (y % 100 == 0 && y % 400 == 0));
    }

    static int OriYear, OriMon, OriDay;
    static int[] MonthDay1 = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
    static int[] MonthDay2 = { 0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
    static int AnsDay = 0;

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        OriYear = scan.nextInt();
        OriMon = scan.nextInt();
        OriDay = scan.nextInt();
        scan.close();
        int d = OriDay, m = OriMon;
        for (int y = OriYear; y <= 2021; y++) {
            int toM = (y == 2021 ? 10 : 12);
            for (; m <= toM; m++) {
                int temp = IsLeapYear(y) ? MonthDay2[m] : MonthDay1[m];
                if (y == 2021 && m == 10)
                    temp = 24;
                for (; d <= temp; d++) {
                    AnsDay++;
                }
                d = 1;
            }
            m = 1;
        }
        System.out.println(AnsDay);
    }
}

C++版本:

#include <iostream>
using namespace std;
bool IsLeapYear(int y) { return (y % 4 == 0 || (y % 100 == 0 && y % 400 == 0)); }
int OriYear, OriMon, OriDay;
int MonthDay1[15] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int MonthDay2[15] = {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int AnsDay = 0;
int main() {
    cin >> OriYear >> OriMon >> OriDay;
    int d = OriDay, m = OriMon;

    for (int y = OriYear; y <= 2021; y++) {
        int toM = (y == 2021 ? 10 : 12);

        for (; m <= toM; m++) {

            int temp = IsLeapYear(y) ? MonthDay2[m] : MonthDay1[m];
            if (y == 2021 && m == 10)
                temp = 24;

            for (; d <= temp; d++) {
                AnsDay++;
            }
            d = 1;
        }
        m = 1;
    }
    cout << AnsDay;
    return 0;
}

解题思路:炒鸡简单,三重循环直接解决。最外层是Year内层是Month,最内层是Day。

今天也是懒惰的小熊一天,爱关注不关注

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值