这几天实训无聊,碰巧蓝桥杯赛又要开始报名了,无聊就刷了刷蓝桥杯练习系统的题,还都是以前做过的题目。
做到第三题:十六进制转八进制
没多想就把第二题的代码复制过来改了改就提交了,用的是 getchar() 输入得到字符串中的每一个字符,超时!!!!!
//#include <iostream>
#include <algorithm>
#include <cstdio>
#include <ctime>
#include <cstring>
using namespace std;
//void toEight(long long n) {
// if( n == 0 ) {
// return;
// }
// toEight(n/8);
// printf("%d", n%8);
//}
int main()
{
// int T;
// scanf("%d", &T);
// getchar();
char ch;
// while( T-- ) {
long long num = 0;
double start = clock();
while( ch = getchar() ) {
if( ch == '\n' ) {
break;
}
if( '0' <= ch && ch <= '9' ) {
num = num*16 + (ch-'0');
} else {
switch( ch ) {
case 'A':
num = num*16 + 10;
break;
case 'B':
num = num*16 + 11;
break;
case 'C':
num = num*16 + 12;
break;
case 'D':
num = num*16 + 13;
break;
case 'E':
num = num*16 + 14;
break;
case 'F':
num = num*16 + 15;
break;
}
}
}
printf("%d\n", num);
printf("%f\n", (double)(clock()-start)/CLOCKS_PER_SEC);
// toEight(num);
// putchar('\n');
// }
return 0;
}
改成先用cin输入得到整个字符串,再对得到的字符串遍历处理,就不超时通过了!!!!印象中 c语言的getchar()速度不慢啊,而且上面的程序还精简点,省去了存储的步骤,按道理来说应该更快的,不懂!!!
#include <iostream>
#include <algorithm>
//#include <cstdio>
#include <ctime>
#include <cstring>
using namespace std;
//void toEight(long long n) {
// if( n == 0 ) {
// return;
// }
// toEight(n/8);
// printf("%d", n%8);
//}
int main()
{
// int T;
// scanf("%d", &T);
// getchar();
char ch[30];
// while( T-- ) {
long long num = 0;
cin >> ch;
// double start = clock();
for( int i=0; i<strlen(ch); ++i ) {
if( '0' <= ch[i] && ch[i] <= '9' ) {
num = num*16 + (ch[i]-'0');
} else {
switch( ch[i] ) {
case 'A':
num = num*16 + 10;
break;
case 'B':
num = num*16 + 11;
break;
case 'C':
num = num*16 + 12;
break;
case 'D':
num = num*16 + 13;
break;
case 'E':
num = num*16 + 14;
break;
case 'F':
num = num*16 + 15;
break;
}
}
}
cout<< num << endl;
// printf("%d\n", num);
// cout << (clock()-start)/CLOCKS_PER_SEC << endl;
// toEight(num);
// putchar('\n');
// }
return 0;
}