原理
衆所周知, 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');
}
相關文章
輸入優化(快讀):https://blog.csdn.net/Ljnoit/article/details/104161565