Search code examples
cperformancebit-manipulationbit-shift

What is the actual meaning of this expression `n = (n<<3)+(n<<1) + ch-'0', ch=getchar_unlocked();`?


In many solutions on codechef for faster input output I came across this expression but I am unable to understand it as I do not have a lot of experience.

inline int scan( ) {

int n=0;

int ch=getchar_unlocked();

while( ch <48 )ch=getchar_unlocked();

while( ch >47 )

n = (n<<3)+(n<<1) + ch-'0', ch=getchar_unlocked();

return n;

}

In the above function what is the purpose of the below mentioned expression?

n = (n<<3)+(n<<1) + ch-'0', ch=getchar_unlocked();

and what is the meaning of (n<<3)+(n<<1)?


Solution

  • If your input stream consists of characters 0-9, then the code block

    while( ch >47 )
      n = (n<<3)+(n<<1) + ch-'0', ch=getchar_unlocked();
    

    computes the decimal integral number from the string as long as ch < 58, which is '9'. If ch >= 58, the result is non-sensical.

    Let's say the first character when entering the loop is 8. Then,

      n = (n<<3)+(n<<1) + ch-'0' = 8
    

    Let's say the second character is 5. Then,

      n = (n<<3)+(n<<1) + ch-'0' = 85
    

    and so on.