I have just finished working on a problem on hackerrank dealing with time conversion in C++.
I'm still fairly new to programming as I only have a few semesters of programming classes under my belt and had a pretty challenging time with this program.
Below is a link to the problem itself and my code. I solved the problem but I feel like my time complexity is unnecessarily high. It works to solve all the test cases the site provides but I am looking to become a better developer so I want to learn to write more efficient and effective code.
Input Format
A single string containing a time in 12-hour clock format (i.e.:
hh:mm:ssAM
orhh:mm:ssPM
), where01 <= hh <= 12
.
Output Format
Convert and print the given time in 24-hour format, where
00 <= hh <= 23
.
Please tell show me how I can optimize this code for a better run time.
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <sstream>
#include<iomanip>
using namespace std;
int main(){
string time;
cin >> time;
char delim = ':'; // delimiter for extracting colons from input
stringstream newTime; // stream to read string that holds time info
newTime << time;
int hours,minutes,seconds; // variables to hold data
string ampm;
newTime >> hours;
newTime >> delim;
newTime>> minutes;
newTime >> delim;
newTime>> seconds;
newTime>> ampm;
if(ampm == "PM"){ // for changing hours to 0-23 scale
switch(hours){
case 1:hours = 13;
break;
case 2:hours = 14;
break;
case 3:hours = 15;
break;
case 4:hours = 16;
break;
case 5:hours = 17;
break;
case 6:hours = 18;
break;
case 7:hours = 19;
break;
case 8:hours = 20;
break;
case 9:hours = 21;
break;
case 10:hours = 22;
break;
case 11:hours = 23;
break;
}
}
else if(ampm == "AM" && hours == 12 ){ // for changing 12am to 00am
hours = 0;
}
//use of iomanip functions below to received desired output
cout << setw(2)<< setfill('0') << hours << ":" << setw(2)<< setfill('0') << minutes << ":" << setw(2)<< setfill('0') << seconds << endl;
return 0;
}