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?
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.


If it is AM and the hours read 12, set hh = "00". Otherwise do nothing.
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 -&gt; 00:mm:ss
        hh = "00";
    }
} else if (h != 12) {
    // 12:mm:ssPM -&gt; 12:mm:ss, otherwise add 12 hours.
    hh = to_string(h + 12);
}

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