快读快写是什么?怎么写?可以用来卡常吗?

Part 0:前言

突发奇想,来介绍快读快写。

希望大家喜欢!😉

Part 1:快读快写是什么?

因为getchar()putchar()很快,所以我们可以利用这个把输入输出的速度提到很快。

Part 2:怎么写?

Part 2.1:快读

写法:

首先定义函数int read()

既然是读入整数,那么就要把多余的空格和负数考虑到:

int f=1;
char ch=getchar();
while(ch<'0'||ch>'9'){
	if(ch=='-')
	f=-1;
	ch=getchar();
}

然后边输入边加在一个变量上:

int s=0;
while(ch>='0'&&ch<='9'){
	s=s*10+ch-'0';
	ch=getchar();
}

这里还不够快,把s*10改成位运算:(s<<1+s<<3)

最后输出(别忘把负数的情况考虑上):return s*f

完整代码:

int read(){
	int s=0,f=1;
	char ch=getchar();
	while(ch<'0'||ch>'9'){
		if(ch=='-')
			f=-1;
		ch=getchar();
	}
	while(ch>='0'&&ch<='9'){
		s=(s<<1+s<<3)+ch-'0';
		ch=getchar();
	}
	return s*f;
}

解析:

  • 定义函数和变量。
  • while()输入直到-或数字,记录负数的情况。
  • while()边输入边累加。
  • return返回值。

Part 2.2:快写

递归写法,比较简单。

完整代码:

void write(int x){
    if(x<0){
    	putchar('-');
		x=-x;
	}
    if(x>9) 
		write(x/10);
    putchar(x%10+'0');
}

Part3:可以用来卡常吗?

可以。

posted @ 2022-08-08 19:11  ForeverCC  阅读(190)  评论(0编辑  收藏  举报
Live2D