快速读入
在算法竞赛中我们时常需要读入大量的数据
而getchar的读入要比scanf快
所以快速读入出现了
快速读入是将每个数以字符串的形势一位一位读入,再转化为数字的算法
如数字48
1.先读入‘4’,数字字符的ascii码与数字相差48 即’4‘ - 48 = 4 或者 ’4‘ - ’0‘ = 4(‘0’的ascii为48)此时x为4
2.再读入‘8’ x = x * 10 + ‘8’ - 48 得到48
3.return x * f
f是如果判断到有负号变为-1使返回的数为负数
int read()
{
int x = 0 , f = 1;
char ch = getchar();
while(ch < '0' || ch > '9'){if(ch == '-') f = -1;ch = getchar();} \\判断负数
while(ch >= '0' && ch <= '9') {x = x * 10 + ch - 48;ch = getchar();}
return x * f;
}
超long long 的数的读入
在某些题目中,有大小超过 1 0 1000 10^{1000} 101000的数需要读入,但往往是对 p p p取模意义下的,这个时候我们可以利用快速读入的取模读入。
int read()
{
int x = 0 , f = 1;
char ch = getchar();
while(ch < '0' || ch > '9'){if(ch == '-') f = -1;ch = getchar();} \\判断负数
while(ch >= '0' && ch <= '9') {x = (x * 10 + ch - 48) % p; ch = getchar();}
return x * f;
}