Codeup 1928 日期差值
题目描述:输入两个日期,返回相差天数
input:
20130101
20130105
output:
5
思路
-
首先假设第一个日期比第二个日期小,若不是,则互换位置
if(time1 > time2 ){ int temp= time1; time1 =time2; time2 = temp; }
-
处理平闰年
- 建立二维数组,按照[月份][平/闰]的下标存储
int month[13][2]={{0,0} , {31,31} , {28,29},{31,31},{30,30},{31,31},{30,30},{31,31},{31,31},{30,30},{31,31},{30,30},{31,31}};
bool isLeap(int year){ return (year % 4==0 && year % 100!=0) ||(year % 400 == 0);
}
```
2. 也可以使用散列表存储
- 处理时间戳
- 将年月日按变量分开
y1 = time1 / 10000 , m1=time1%10000 /100 ,d1 = time1 % 100; y2 = time2 / 10000 , m2=time2%10000 /100 ,d2 = time2 % 100;
- 循环递增日期,若到达该月最大值,转1,月+1
- 循环递增月,若到达13,转1,年+1
while(y1 < y2 || m1 < m2 || d1< d2){ d1++; if(d1==month[m1][isLeap(y1)] +1){ m1 ++; d1 = 1; } if(m1 == 13 ){ y1++; m1 =1; } ans++; }
- 总循环次数就是相差的天数
加油!!!