0

以下代码用于打印int. 如何修改它以打印long long int?请解释。

对于pc, 阅读putchar_unlocked

inline void writeInt (int n)
{
    int N = n, rev, count = 0;
    rev = N;
    if (N == 0) { pc('0'); pc('\n'); return ;}
    while ((rev % 10) == 0) { count++; rev /= 10;}
    rev = 0;
    while (N != 0) { rev = (rev<<3) + (rev<<1) + N % 10; N /= 10;}
    while (rev != 0) { pc(rev % 10 + '0'); rev /= 10;}
    while (count--) pc('0');
    pc('\n');
    return ;
}
4

2 回答 2

6

代码中没有关于 int 的具体内容。只需将两次出现的“int”都替换为“long long int”,就完成了。

(我通过 shift 发现 *10 的“优化”,并添加了所有剩余的分区非常荒谬。任何体面的 C 编译器都会自动执行此操作(以及更多)。并且不要忘记针对此“快速”版本进行分析stdlib 例程,以确保它确实值得付出努力)。

于 2013-01-06T23:49:48.153 回答
5

这段代码比它需要的要复杂一点:

inline void writeLongLong (long long n)
{
    char buffer[sizeof(n) * 8 * 3 / 10 + 3];  // 3 digits per 10 bits + two extra and space for terminating zero. 
    int index = sizeof(buffer)-1;
    int end = index;
    buffer[index--] = 0;
    do {
       buffer[index--] = (n % 10) + '0';
       n /= 10;
    } while(n);
    puts(&buffer[index+1]);
}

这做同样的工作,大约一半的除法/模运算,至少我可以更好地遵循它。请注意,stdio/stdlib 函数可能比这更好,并且此函数不能处理负数(上面发布的函数也不处理)。

于 2013-01-07T00:03:43.517 回答