【C++】输出优化(快写)

原理

众所周知, putchar() 是用来输出单个字符的函数。
因此将数字的每一位转化为字符输出以加速。
要注意的是,负号要单独判断输出,并且每次 %(mod)取出的是数字末位,因此要倒序输出

代码实现

一般的快写:

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

但是递归实现常数是较大的,我们可以写一个栈来实现这个过程:

inline void write(int x) {
	static int sta[35];
	int top=0;
	do {
		sta[top++]=x%10, x/=10;
	} while(x);
	while(top) putchar(sta[--top]+'0');
}

不分整数类型的快写:

template <typename T>
inline void write(T x) {
    if(x<0) putchar('-'),x=-x;
    if(x<10) putchar(x+'0');
        else write(x/10),putchar(x%10+'0');
}

fwrite

#include <cctype>
#include <cstdio>

typedef long long LL;

#define bsiz 1000000

int sta[30];
char buf[bsiz], pbuf[bsiz], *p = pbuf, *s = buf, *t = buf;

#define mputc(ch) (p - pbuf == bsiz ? fwrite(pbuf, 1, bsiz, stdout), p = pbuf, *p++ = ch : *p++ = ch)

inline void putll(LL x) {
    register int top = 0;
    if (x<0) mputc('-'), x = -x;
        do sta[top++] = x % 10, x /= 10;
    while (x);
    while (top) mputc(sta[--top] + '0');
}

int main() {
    LL ans=123;
	putll(ans);
    fwrite(pbuf, 1, p - pbuf, stdout);
    printf("\n");
	return 0;
}

相关文章

输入优化(快读):https://blog.csdn.net/Ljnoit/article/details/104161565

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值