關於getchar() 和 cin 輸入字符串的速度問題

這幾天實訓無聊,碰巧藍橋盃賽又要開始報名了,無聊就刷了刷藍橋杯練習系統的題,還都是以前做過的題目。

做到第三題:十六進制轉八進制

沒多想就把第二題的代碼複製過來改了改就提交了,用的是 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;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章