- 題目描述:
-
有兩個日期,求兩個日期之間的天數,如果兩個日期是連續的我們規定他們之間的天數爲兩天
- 輸入:
-
有多組數據,每組數據有兩行,分別表示兩個日期,形式爲YYYYMMDD
- 輸出:
-
每組數據輸出一行,即日期差值
- 樣例輸入:
-
20110412 20110422
- 樣例輸出:
-
11
-
-
思路:
-
寫一個caldays的函數,計算該年月日離該年1月1日的日期差值,判斷兩個日期是否屬於同一年,是,則直接去caldays的差值
-
否,則加上年的日子數
-
-
Code:
-
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <stdio.h>
#include <math.h>
bool
Judge(
int
year) {
if
(year % 100 == 0) {
if
(year % 400 == 0) {
return
true
;
}
else
{
return
false
;
}
}
else
{
if
(year % 4 == 0) {
return
true
;
}
else
{
return
false
;
}
}
}
std::vector<
int
> normal_month;
// = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
std::vector<
int
> special_month;
// = { 0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
int
CalDays(
int
year,
int
month,
int
day) {
int
result = 0;
if
(Judge(year)) {
for
(
int
i = 1; i < month; i++) {
result += special_month[i];
}
result += day-1;
}
else
{
for
(
int
i = 1; i < month; i++) {
result += normal_month[i];
}
result += day-1;
}
return
result;
}
int
main() {
normal_month.push_back(0); normal_month.push_back(31); normal_month.push_back(28); normal_month.push_back(31); normal_month.push_back(30); normal_month.push_back(31); normal_month.push_back(30); normal_month.push_back(31); normal_month.push_back(31); normal_month.push_back(30); normal_month.push_back(31); normal_month.push_back(30); normal_month.push_back(31);
special_month.push_back(0); special_month.push_back(31); special_month.push_back(29); special_month.push_back(31); special_month.push_back(30); special_month.push_back(31); special_month.push_back(30); special_month.push_back(31); special_month.push_back(31); special_month.push_back(30); special_month.push_back(31); special_month.push_back(30); special_month.push_back(31);
int
date1, date2;
int
gap;
while
(std::cin >> date1) {
std::cin >> date2;
int
start_date = date1 > date2 ? date2 : date1;
int
end_date = date1 > date2 ? date1 : date2;
int
start_year = start_date / 10000;
int
end_year = end_date / 10000;
int
start_month = (start_date - start_year * 10000) / 100;
int
end_month = (end_date - end_year * 10000) / 100;
int
start_day = start_date % 100;
int
end_day = end_date % 100;
int
day_s = CalDays(start_year, start_month, start_day);
int
day_e = CalDays(end_year, end_month, end_day);
if
(start_year == end_year) {
gap = day_e - day_s+1;
}
else
{
// int to_next_year11 = Judge(start_year) ? 365-day_s: 366-day_s;
gap = 0;
for
(
int
i = start_year; i < end_year; i++) {
gap += Judge(i) ? 366 : 365;
}
gap += (day_e - day_s + 1);
}
printf
(
"%d\n"
, gap);
}
}
/**************************************************************
Problem: 1096
User: nick_huang
Language: C++
Result: Accepted
Time:0 ms
Memory:1524 kb
****************************************************************/