# HackerRank Time Conversion solution

The challenge (PDF) is to convert a time from 12-hour format (hh:mm:ssAM or hh:mm:ssPM) to 24-hour format.

This is my solution, which worked for all test cases.

string timeConversion(string s) {
int size = s.length();
if(s[size-2]=='A'){
string hh = s.substr(0,2);
int h = stoi(hh);
if(h==12){
string newh = "00";
string newTime = newh.append(s.substr(2,6));
return newTime;
}else{
return s.substr(0,size-2);
}
}
else{
string hh = s.substr(0,2);
int h = stoi(hh);
if(h==12){
return s.substr(0,size-2);
}
int inPM = h+12;
string newh = to_string(inPM);
string newTime = newh.append(s.substr(2,6));
return newTime;
}
}


Anything which I could have done in a different way in your opinion?

• Please add the HackerRank Question to the question, links have been known to break. – pacmaninbw Jul 29 at 14:52

Since the question gives a couple of guarantees about the input, take advantage of them. If you want to communicate these preconditions, assert them. Something like

string timeConversion(string s) {
// Assume input is in the format hh:mm:ssAM or hh:mm:ssPM
assert(s.length() == 10);
int size = s.length();
...


...
if(s[size-2]=='A'){
string hh = s.substr(0,2);
int h = stoi(hh);
...
else{
string hh = s.substr(0,2);
int h = stoi(hh);
...


You do the same thing no matter which branch is taken. You can hoist this in front of the if statement

string hh = s.substr(0, 2);
int h = stoi(hh);
if (s[8] == 'A') {
...
} else {
...
}


After the previous step, the logic left is fairly straight-forward.

1. If it is AM and the hours read 12, set hh = "00". Otherwise do nothing.
2. If it is PM add the hours read 12, do nothing. Otherwise add 12 to the hours.

This is good. One thing to note is that two paths lead to the same conclusion of do nothing or don't change the time. I would keep the exact same logic and restructure a little to avoid redoing work.

...
if (s[8] == 'A') {
if (h == 12) {
// 12:mm:ssAM -> 00:mm:ss
hh = "00";
}
} else if (h != 12) {
// 12:mm:ssPM -> 12:mm:ss, otherwise add 12 hours.
hh = to_string(h + 12);
}

return hh + s.substr(2, 6);


I think what you have is fine. There are many ways this can be done.

For example:

string timeConversion(string s)
{
int hours = stoi(s.substr(0,2));
if (s[8] == 'A')
{
if (hours == 12) hours = 0;
}
else
{
if (hours == 12) hours = 12;
else hours += 12;
}
return ((hours < 10) ? "0" :"") + to_string(hours) + s.substr(2,6);
}

• This doesn't work for a testcase of the form 12:mm:ssPM as 12 + 12 % 24 == 00 giving an answer of 00:mm:ss but the question states it should be 12:mm:ss. – spyr03 Jul 29 at 15:18
• thanks, fixed via code – Dennis Jul 29 at 15:37