I was doing this easy challenge "Counting Minutes I" from Coderbyte.com where you just calculate the number of minutes between two given times.
The second time is always after the first, although it may look to be before but mean it's during the next day.
The format of their test cases is "hour1:minute1-hour2:minute2"
such as "12:30am-12:00pm"
where the difference would be 11.5 hours = 1425
minutes.
In converting different parts of the string
containing the times to int
s I've been using istringstream
but creating a new one each time I call the function to set the int
s. It seems like this is a sloppy way of accomplishing this, is there a better way like creating one istringstream
in my main CountingMinutesI
function and passing that as an argument to getNum
then clearing it out after setting each particular int
? Or is this also a bad idea?
#include <iostream>
#include <sstream>
using namespace std;
void getNum (string timeString, int& pos, int& result) {
string temp;
while (isdigit(timeString[pos])) {
temp += timeString[pos];
pos++;
}
istringstream iss (temp);
iss >> result;
}
void to24HourTime(string timeString, int& pos, int& hourToConvert) {
if (timeString[pos] == 'p' && hourToConvert != 12)
hourToConvert += 12;
if (timeString[pos] == 'a' && hourToConvert == 12)
hourToConvert = 0;
}
int CountingMinutesI(string str) {
int hour1int, hour2int, min1int, min2int, minDifference;
int stringPos = 0;
getNum(str, stringPos, hour1int);
stringPos++;
getNum(str, stringPos, min1int);
to24HourTime(str, stringPos, hour1int);
stringPos += 3;
getNum(str, stringPos, hour2int);
stringPos++;
getNum(str, stringPos, min2int);
to24HourTime(str, stringPos, hour2int);
if (hour2int < hour1int) //second time is the during the next day
hour2int += 24;
if (hour1int == hour2int && min1int > min2int) //time difference would look negative, but is really between 23 and 24 hours
hour2int += 24;
if (min2int < min1int) { //simplify subtracting minutes to add to total difference
min2int += 60;
hour2int--;
}
minDifference = (hour2int - hour1int) * 60 + (min2int - min1int);
return minDifference;
}
int main() {
// keep this function call here
cout << CountingMinutesI(gets(stdin));
return 0;
}