1+ /* ****************************************************************/ /* *
2+ * \file TimeConversion.cpp
3+ * \brief Test question on HackerRank platform.
4+ * https://www.hackerrank.com/challenges/time-conversion/problem
5+ * Given a time in 12-hour AM/PM format, convert it to 24-hour time.
6+ * Passes all test cases and the code is submitted.
7+ *
8+ * Command used to compile:
9+ * $ g++ -o time.exe .\TimeConversion.cpp -std=c++11
10+ * $ .\time.exe
11+ *
12+ * \author Xuhua Huang
13+ * \date October 2021
14+ *********************************************************************/
15+
16+ #include < iostream>
17+ #include < stdlib.h>
18+ #include < string>
19+
20+ /*
21+ * Complete the 'timeConversion' function below.
22+ *
23+ * The function is expected to return a STRING.
24+ * The function accepts STRING s as parameter.
25+ */
26+ std::string timeConversion (std::string s) {
27+ std::string result = " " ;
28+
29+ if (s.find (" AM" ) != std::string::npos && stoi (s.substr (0 , 2 )) == 12 ) {
30+ result = s.erase (8 , 2 );
31+ result = s.replace (0 , 2 , " 00" );
32+ }
33+ else if (s.find (" PM" ) != std::string::npos && stoi (s.substr (0 , 2 )) == 12 ) {
34+ result = s.erase (8 , 2 );
35+ }
36+ else if (s.find (" AM" ) != std::string::npos) {
37+ result = s.erase (8 , 2 );
38+ }
39+ else if (s.find (" PM" ) != std::string::npos) {
40+ result = s.erase (8 , 2 );
41+ result = s.replace (0 , 2 , std::to_string ((stoi (s.substr (0 , 2 )) + 12 )));
42+ }
43+
44+ return result;
45+ }
46+
47+ int main ()
48+ {
49+ std::string s;
50+ std::getline (std::cin, s); // get the 12-hour format time from the user
51+
52+ std::string result = timeConversion (s);
53+
54+ std::cout << result << " \n " ;
55+
56+ return 0 ;
57+ }
0 commit comments