我刚刚完成了在C++中处理时间转换的hackerrank问题。
我对编程还是相当陌生的,因为我只有几个学期的编程类,并且在这个程序中有相当大的挑战。
下面是问题本身和我的代码的链接。我解决了这个问题,但我觉得我的时间复杂度太高了。它可以解决网站提供的所有测试用例,但我希望成为一个更好的开发人员,所以我想学习如何编写更高效、更有效的代码。
包含12小时时钟格式(即:
hh:mm:ssAM或hh:mm:ssPM)的时间的单个字符串,其中01 <= hh <= 12。
转换并打印24小时格式的给定时间,其中
00 <= hh <= 23.
请告诉我如何优化这些代码以获得更好的运行时间。
#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;
}发布于 2016-05-31 16:42:27
始终在函数顶部执行声明,即使不立即初始化该变量。这有助于您在读取代码时更容易找到变量的类型。
不要使用std命名空间。有关为什么这是错误实践的更多信息,请参见关于堆栈溢出的问题。
与您的空白保持一致。如果在运算符周围使用空格,则在所有运算符周围使用空白。
你在耍弦乐和弦乐。请记住,std::cin也是一个流,所以您可以直接从std::cin读取,完全跳过time和newTime。
std::cin >> hours >> delim >> minutes >> delim >> seconds >> ampm;大开关语句是不必要的。有两种特殊情况:午夜和中午。对于所有其他的PM时间,我们只需添加12。
您根本没有做任何错误检查。您没有检查给定的输入是否在范围内,也没有检查给定的输入是否有意义。
第一个错误很容易检查:只需做一些测试,看看您在hours、minutes和seconds中读取的数字是否在您期望的范围之内。
第二个错误使流处于错误状态。我们可以通过把整件事放在一个if-语句中来捕捉它。
if( !(std::cin >> hours >> delim >> minutes >> delim >> seconds >> ampm) ) {
//Written something in input stream that does not follow this pattern
return 1;
} else if( hours <= 0 || hours > 12 || minutes < 0 || minutes >= 60 || seconds < 0 || seconds >= 60 ) {
//Input not within bounds
return 1;
}你对待任何不是"PM“的字符串,就好像它是"AM”。显然,任何字符串都可以在您的时间之后输入。您应该检查它是"PM“还是"AM",可能与上面的if -语句相同。
你包括了很多图书馆。只需要iostream和iomanip。在您的代码中,您可能也需要sstream。您没有使用向量、数学或c样式的输入/输出(如fprintf ),所以不要包含它们。
https://codereview.stackexchange.com/questions/129771
复制相似问题