c - 在 C 中快速输入 long 和 long long?

标签 c input long-integer long-long large-data

所以我一直在使用这个函数来解决 codechef 问题,现在作为整数的快速输入方法。

我的问题是这实际上是如何工作的,什么是 fgetc_unlocked(stdin)(即使它有注释),最重要的是我如何优化它以运行很长时间。

代码如下:

inline void Scan_f(int a)
{
char c = 0;
while(c<33)//shouldn't value of c to compare be less than 9 as digit vary between 0 to 9?? 
//c = fgetc_unlocked(stdin);
c = getc(stdin);
a = 0;
while(c>33)
{
a = a*10 + c - '0';
//c = fgetc_unlocked(stdin);
c = getc(stdin);
}

最佳答案

在我看来代码应该是:

inline unsigned long long Scan_f()
{
    int c;
    do
        c = fgetc(stdin);
    while ( (c < '0' || c > '9') && c != EOF );

    unsigned long long a = 0;
    while ( c >= '0' && c <= '9' )
    {
        a = a*10 + (c - '0');
        c = fgetc(stdin);
    }
    return a;
}

在您发布的代码中,a是按值传递的参数,因此不清楚调用函数将如何了解您对 a 的更改.

fgetc_unlocked函数应该是 fgetc 的更快版本.这是一个 GNU 扩展。

对于 a 没有意义成为带符号的类型,因为您的解析永远无法检索到负值。

这个版本不检查溢出;如果你想处理这种可能性,那么你需要在执行 a = a*10 之前添加一个支票。 .

不用担心 c < '0' 的效率等部分,编译器会为你生成最佳代码。他们可以很好地处理像这样的简单情况。当然,它可以比从任何输入流中读取字符更快地检查它;输入流速度将成为瓶颈。

关于c - 在 C 中快速输入 long 和 long long?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22903167/

相关文章:

c++ - DBL_MAX 加法是如何工作的?

c - 使用 printf 格式化列

arrays - 通过结构访问数组(使用指针)

java - 带有数组的 Java.Util.Scanner 的 NoSuchElementException

c - 如何从 C 中的 1 和 0 数组中获取十六进制数?

c++ - 在 C++ 中从 cin 按下 ESC 按钮之前如何读取符号

html - 我将如何在 div 的中心对齐我的输入框?

c++ - 你如何在 visual studio 中预览你的 c++ 代码

Java程序长数组中的数字格式异常?

c++ - 从 'int' 到 'long int' 性能显着下降