题解 | #日期差值#

日期差值

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

#include <iostream>

using namespace std;

int dayTable[2][13] ={
	{0,31,28,31,30,31,30,31,31,30,31,30,31},
	{0,31,29,31,30,31,30,31,31,30,31,30,31}
};

int total[2] = {365, 366};

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

int main () {
	char a[9], b[9];
	int y1, y2, m1, m2, d1, d2;
	int sum1 = 0, sum2 = 0;
	cin >> a >> b; 
	sscanf(a, "%04d%02d%02d", &y1, &m1, &d1);
	sscanf(b, "%04d%02d%02d", &y2, &m2, &d2);
	for (int i = 0; i < m1; i++){
		sum1 += dayTable[isLeapYear(y1)][i];
	}
	sum1 += d1;
	for (int i = 0; i < m2; i++){
		sum2 += dayTable[isLeapYear(y2)][i];
	}
	sum2 += d2;
	int sum = sum2 - sum1 + 1;
	int ygap = y2 - y1;
	while (ygap > 0){
		sum += total[isLeapYear(y2)];
		ygap--;
	}
	cout << sum << endl;
	return 0;
}

全部评论

相关推荐

点赞 评论 收藏
分享
努力成为C语言高手:质疑大祥老师,理解大祥老师,成为大祥老师
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务