题解 | #日期累加#
日期累加
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'))