Hackerrank Time Conversion (C++)

C++ :

string timeConversion(string s) {
     * Write your code here.
    int pos = s.find("PM"), hour = 0;
    string formattedTime = "", twelveAm = "00";
    if(pos == -1){
        pos = s.find("AM");
        hour = stoi(s.substr(0, 2));
        if(hour == 12){
            formattedTime = s.replace(0, 2, twelveAm);
            formattedTime = s;
        formattedTime = formattedTime.substr(0, pos);
        hour = stoi(s.substr(0, 2));
        if(hour != 12){
            hour += 12;
        formattedTime = s.replace(0, 2, to_string(hour));
        formattedTime = formattedTime.substr(0, pos);

    return formattedTime;


Ok, this problem gave quite some headaches with the corner cases of 12PM and 12AM. Had to use some hackos to see the corner cases missed.

But first, the general idea is to find out if the input string is AM or PM. Using string.find(“some string”), find if “PM” is present in string s, if not it is an “AM” time. If string is AM, use stoi to convert the first two string input into an integer with stoi, then check if it’s 12 (am). If it’s 12, replace “12” with “00” in string, then use substring again to remove “AM” from the string.

Otherwise, the time is in PM. Firstly, check if hour is “12” using similar methods to AM. If it’s not 12, add 12 to make it a 24 hour format, otherwise leave it at 12. Convert hour to from an integer to a string with to_string, then use substring again to push the 24-hour format into formattedTime.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *