题解 | #日期差值#

日期差值

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

#include<iostream>
#include<map>
using namespace std;

//习题2.6 日期差值
int isLearYear(int year) {
	if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
		return 1;
	}
	return 0;
}

int main()
{
	//20110412
	//20110422
	int a, b;
	cin >> a >> b;
	if (a > b) {
		int temp = a;
		a = b;
		b = temp;
	}
	map<int, int> maps = { {1,31},{2,28},{3,31},{4,30},{5,31},{6,30},{7,31},{8,31},{9,30},{10,31},{11,30},{12,31} };
	int y1 = a / 10000, m1 = (a % 10000) / 100, d1 = (a % 10000) % 100;
	int y2 = b / 10000, m2 = (b % 10000) / 100, d2 = (b % 10000) % 100;

	int res1 = 0, res2 = 0;
	//计算较小的日期在那一年的第几天
	for (int i = 1; i < m1; i++) {
		if (isLearYear(y1) == 1 && i == 2) {
			res1 += (maps[i]+1);
		}
		else {
			res1 += maps[i];
		}
	}
	res1 += d1;

	//先计算较大日期相差的年份的天数
	for (int i = y1; i < y2; i++) {
		if (isLearYear(i) == 1) {
			res2 += 366;
		}
		else {
			res2 += 365;
		}
	}

	for (int i = 1; i < m2; i++) {
		if (isLearYear(y2) == 1 && i == 2) {
			res2 += (maps[i] + 1);
		}
		else {
			res2 += maps[i];
		}
	}
	res2 += d2;

	cout << abs(res2 - res1) + 1 << endl;

	return 0;
}

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务