-3

如何将字符串操作为整数以及按位运算符的用途..此函数已在 c 中用于从数字字符串中获取输入

    "gc and ll are defined like this.. typedef long long LL; 
     #define gc getchar_unlocked()"

inline LL inp()
{
LL num = 0;
char p = gc;
while(p<33)p=gc;
while(p>33) {
    num = (num << 3)+ (num << 1)+ (p -'0');
    p = gc;
}
return num;
};
4

1 回答 1

2

我收集char p = gcinput.

while(p<33)p=gc;只是不断输入,直到输入除空格以外的其他内容?(空格是十进制的第 32 个字符)。

然后,虽然输入不是空格,

(num << 3) + (num << 1)等价于num * 10(num << 3等价于num * 8,num << 1等价于num * 2,num * 8 + num * 2可以写成num * (8+2)化简为num * 10)。

p - '0'将输入字符(例如 '9' [char 57])转换为相应的整数(例如,仅 9)。

如果输入为“123”,则 num 将等于 123,因为:

数 = 0;

数 = 0 * 10 + 1;(== 1)

数 = 1 * 10 + 2;(== 12)

数 = 12 * 10 + 3;(== 123)

我希望这能带来一些启示。这是一个非常糟糕的代码,如果输入数字 0-9 以外的任何其他内容,它将无法正常运行。

像这样写可能会更好:

// function to read one character from the 'input'
char gc();

// I'm not sure what LL is here, could be long long?
inline LL inp()
{
    LL num = 0;
    char p = gc();

    // keep reading characters until a number is encountered
    while((p < '0') || (p > '9'))
    {
        p = gc();
    }

    // loop until a non-number is encountered
    while((p >= '0') && (p <= '9'))
    {
        // Shift the previously read digits up by one 'tens' column
        num *= 10;

        // Add in the newly read digit
        num += p -'0';

        // Read the next character
        p = gc();
    }

    return num;
}
于 2013-09-29T09:39:29.830 回答