while( ch >= ‘0’ && ch <= ‘9’ )
n = (n<<3)+(n<<1) + ch-‘0’,ch=getcx();
#define getcx getchar //this has been defined at the beginning
Can someone please explain to me what does the above code mean ? Specifically, I dont understand n<<3 , n<<1 .
while( ch >= ‘0’ && ch <= ‘9’ )
n = (n<<3)+(n<<1) + ch-‘0’,ch=getcx();
#define getcx getchar //this has been defined at the beginning
Can someone please explain to me what does the above code mean ? Specifically, I dont understand n<<3 , n<<1 .
k<<l is the same as k*2^l ( ^ is power ).
k>>l is the same as k/2^l (integer dividing : 3/2=1, 100/99 = 0)
It is called bitwise shift.
Examples :
1<<2 = 1 * 2^2 = 1 * 4 = 4
1<<3 = 1 * 2^3 = 1 * 8 = 8
3<<4 = 3 * 2^4 = 3 * 16 = 48
3>>4 = 3/2^4 = 3/16 = 0
It is called shift, beacuse every time you shift binary representation of number by one.
Ex.: (in binary)
a = 10010001
a<<1 = 100100010
a<<2 = 1001000100
a<<3 = 10010001000
…
a = 10010001
a>>1 = 1001000
a>>2 = 100100
a>>3 = 10010
a>>4 = 1001
a>>5 = 100
a>>6 = 10
a>>7 = 1
a>>8 = 0
…
n=(n<<3)+(n<<1)+ch-‘0’ =(n.2^3)+(n.2^1)+ch-‘0’=n.(8+2)+ch-‘0’=10n +ch-‘0’
All clear . Thanks a lot.