HackerRank/Algorithm/Time Conversion

Problem Summary

Given a time in 12-hour AM/PM format, convert it to 24-hour time.

About the 12-hour clock:

https://en.wikipedia.org/wiki/12-hour_clock

Solution

Note that Midnight is 12:00:00AM on a 12-hour clock, and 00:00:00 on a 24-hour clock, and similarly, noon is 12:00:00PM on a 12-hour clock and 12:00:00 on a 24-hour clock.
Once we know this, the coding is trivial.

Code

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
26
27
28
29
30
#include <iostream>
#include <cstring>
using namespace std;
string timeConversion(string s) {
string t(s,0,8);
int h = (s[0]-'0')*10 + s[1]-'0';
if(s[8]=='A' && h==12)
h=0;
else
if(s[8]=='P' && h<12)
h+=12;
t[0] = '0' + h/10;
t[1] = '0' + h%10;
return t;
}
int main() {
string s;
cin >> s;
string result = timeConversion(s);
cout << result << endl;
return 0;
}