【发布时间】:2013-08-05 14:56:30
【问题描述】:
我找到了这个用于快速 I/O 的代码。
#include <cstdio>
inline void fastRead_int(int &x) {
register int c = getchar_unlocked();
x = 0;
int neg = 0;
for(; ((c<48 || c>57) && c != '-'); c = getchar_unlocked());
if(c=='-') {
neg = 1;
c = getchar_unlocked();
}
for(; c>47 && c<58 ; c = getchar_unlocked()) {
x = (x<<1) + (x<<3) + c - 48;
}
if(neg)
x = -x;
}
inline void fastRead_string(char *str)
{
register char c = 0;
register int i = 0;
while (c < 33)
c = getchar_unlocked();
while (c != '\n') {
str[i] = c;
c = getchar_unlocked();
i = i + 1;
}
str[i] = '\0';
}
int main()
{
int n;
char s[100];
fastRead_int(n);
printf("%d\n", n);
fastRead_string(s);
printf("%s\n", s);
return 0;
}
为什么会有位移 (x
【问题讨论】:
-
没有任何上下文或函数正在做什么,很难知道这些按位运算在做什么。如果有帮助的话,左移一位与乘以 2 相同,左移三位与乘以 8 相同。
-
我已经添加了完整的代码。这是博文:digital-madness.in/blog/2013/fast-io-in-c/#comment-2137 基本上这种方法用于竞争性编程以实现更快的 I/O。
-
(x<<1) + (x<<3)等于乘以10。如果你用十进制表示一个数字,那就是“左屎”(例如:12 * 10 = 120)。c - 48在末尾添加新数字。 -
不就是简单的乘以10(8x + 2x = 10x)吗?我敢打赌,如果有益的话,编译器可以做这种优化。
-
考虑两个值的简单输入。
'2'和'3'。从x=0开始,第一遍只将2存储在x中。第二遍会将3添加到值(2<<1 + 2<<3),即(4+16) + 3或(20) + 3。 IE。 23. 换句话说,这是将前一个值乘以10,然后将下一个字符添加为十进制个位数。
标签: c++ c io bitwise-operators