简体   繁体   中英

How to get input using the left-shift-bitwise operator?

#include<stdio.h>

long scan()
{
    long int t = 0;
    char c;
    c = getchar_unlocked();
    while (c < '0' || c>'9')
        c = getchar_unlocked();
    while (c >= '0' && c <= '9')
    {
        **t = (t << 3) + (t << 1) + c - '0'; **
            c = getchar_unlocked();
    }
    return(t);
}

int main()
{
    int t, a[110], n, i; long long int c, sum;
    t = scan();
    while (t--)
    {
        sum = 0;
        scanf("%d%lld", &n, &c);
        for (i = 0; i < n; i++)
        {
            a[i] = scan();
            sum += a[i];
        }
        if (sum <= c) 
            printf("Yes\n");
        else 
            printf("No\n");
    }
    return 0;
}

Please help me understand the line in '**'. I know that left shift operator n multiplies the number by 2^n. So t is first getting multiplied by 8, then by 2. But how is that helping us get the input?

The scan() function gets the input and returns it.

The line you indicated with the asterisks doesn't help get input, all it does it update the value of the variable t based on the current value of c .

It is the calls to getchar_unlocked() that get the next character from stdin and return it, and the program stores that value in the variable c .

The program expects that the characters will be numeric ASCII digits, so that the computed value of (c-'0') will be between 0 and 9 inclusive. For each of those value values, it does the equivalent of t = (t*8) + (t*2) + the_computed_value; -- I'm not sure what the intent is, but that's what it's doing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM