题解 | #日期累加#

日期累加

https://www.nowcoder.com/practice/eebb2983b7bf40408a1360efb33f9e5d

//C++版代码
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
    int m;
    cin >> m;
    int days[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    while (m--) {
        int year, month, day, add;
        cin >> year >> month >> day >> add;
        while (add--) {
            days[2] = year % 4 == 0 && year % 100 != 0 || year % 400 == 0 ? 29 : 28;
            day++;
            if (day > days[month]) {
                day = 1;
                month++;
                if (month > 12) {
                    month = 1;
                    year++;
                }
            }
        }
        cout << year << '-' << setw(2) << setfill('0') << month << '-' << setw(
                 2) << setfill('0') << day << endl;
    }
    return 0;
}
//Java版代码
import java.time.LocalDate;
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int m = sc.nextInt();
        while (m-- != 0) {
            int year = sc.nextInt();
            int month = sc.nextInt();
            int day = sc.nextInt();
            int add = sc.nextInt();
            LocalDate date = LocalDate.of(year, month, day).plusDays(add);
            System.out.printf("%4d-%02d-%02d", date.getYear(), date.getMonthValue(), date.getDayOfMonth());
        }
    }
}
//Python版代码
from datetime import datetime, timedelta
for _ in range(int(input())):
    year, month, day, add = map(int, input().split())
    print((datetime(year, month, day) + timedelta(add)).strftime('%Y-%m-%d'))

全部评论

相关推荐

头像
11-21 11:39
四川大学 Java
是红鸢啊:忘了还没结束,还有字节的5k 违约金
点赞 评论 收藏
分享
1 收藏 评论
分享
牛客网
牛客企业服务