关于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;
}


  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值