dhyan
September 25, 2013, 1:58pm
1
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:
n = 0
you read β1β and convert it to number β1β - β0β = 1 => n = 1
you read β2β and convert it to number β1β - β0β = 1 => n = 10 * n + 2 = 12
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
4 Likes
dhyan
September 25, 2013, 3:10pm
3
@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.
vaka
September 27, 2013, 3:31am
5
@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