# C: A goddamn function for integer input

I am a newbie in codechef.
Can anybody help me to understand how this function works?

``````int inputlarge( )
{
int n=0;
int ch=getchar_unlocked();
while( ch >= '0' && ch <= '9' )
n = (n<<3)+(n<<1) + ch-'0'; ch=getchar_unlocked();
return n;
}``````

Imagine, you can read input just char by char, so you have to do the math to get correct input… Suppose you want to read number 123:

1. n = 0
2. you read ‘1’ and convert it to number ‘1’ - ‘0’ = 1 => n = 1
3. you read ‘2’ and convert it to number ‘1’ - ‘0’ = 1 => n = 10 * n + 2 = 12
4. you read ‘3’ and convert it to number ‘1’ - ‘0’ = 1 => n = 10 * n + 3 = 123

and you know, that 10 = 8 + 2 and with bit operations n = 10 * n + c = 8 * n + 2 * n + c = n << 3 + n << 1 + c

6 Likes

@betlista thanks a lot.
I was confused with those left shift operations

Supposedly that shift operation does the same as x = x * 10, i’ve never proven it, though.

@c0d3junki3 There is nothing really to prove here it just follows from what left shift does. Every left shift multiplies the number by 2 as long as it doesn’t exceed the number range. So (n<<3) is same as 8n and (n<<1) is same as 2n.

1 Like
//