这个函数如何从输入工作中读取数字?

时间:2013-09-29 09:29:34

标签: c string

如何将字符串操作为整数以及如何使用按位运算符..此函数已在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;
};

1 个答案:

答案 0 :(得分:2)

我认为char p = gcinput获得了一个角色。

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

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

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

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

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

num = 0;

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

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

num = 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;
}