-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 = gcから文字を取得するものを集めinputます。

while(p<33)p=gc;スペース以外の何かが入力されるまで、入力を取得し続けますか? (スペースは 10 進数で 32 文字です)。

次に、入力はスペースではありませんが、

(num << 3) + (num << 1)と等価ですnum * 10(num << 3は と等価ですnum * 8num << 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 に答える