我们运用字符串来输入这两个时间点。那么所输入的一个时间的字符长度为 $8$(XX:XX:XX)。那么我们把两个时间统一单位为秒钟后作差,然后再进行求解。那么我们设输入的一个字符串为 str,再分别来看时分秒。

  • 时:(str[0] - '0') * 10 + str[1] - '0'
  • 分:(str[3] - '0') * 10 + str[4] - '0'
  • 秒:(str[6] - '0') * 10 + str[7] - '0'

然后将这些内容分别 $\times 3600,60,1$ 则能得到统一单位的时间和。然后我们将两者作差。则会有 $3$ 种情况:

  • str_end - str_start > 0,直接进行转换输出即可。
  • str_end - str_start == 0,由题可知正好为 $24$ 个小时,需要特判输出。
  • str_end - str_start < 0,即跨了一天,需要加上 $24$ 个小时(也就是 $24 \times 3600$ 秒)。

最后就是输出了,记得输出 $0$ 的特殊情况,在此不赘述。代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <bits/stdc++.h>
using namespace std;
int main()
{
string a,b;int ans = 0;
cin>>a>>b;
//start与end的时间求和(单位:秒)
int timea = ((a[0] - '0') * 10 + a[1] - '0') * 3600 + ((a[3] - '0') * 10 + a[4] - '0') * 60 + ((a[6] - '0') * 10 + a[7] - '0');
int timeb = ((b[0] - '0') * 10 + b[1] - '0') * 3600 + ((b[3] - '0') * 10 + b[4] - '0') * 60 + ((b[6] - '0') * 10 + b[7] - '0');
ans = timeb - timea;//作差
if(timea == timeb)//特判
{
cout<<"24:00:00"<<endl;
return 0;
}
if(timea > timeb) ans += 24 * 3600;//隔了一天
//换算输出,注意0的情况
if(ans / 3600 < 10) cout<<"0";
cout<<ans / 3600<<":";
if(ans % 3600 / 60 < 10) cout<<"0";
cout<<ans % 3600 / 60<<":";
if(ans % 3600 % 60 < 10) cout<<"0";
cout<<ans % 3600 % 60<<endl;
return 0;
}