IT IS A CONCEPTUAL QUESTION -> plz answer in detail
if(i==1) compares the value held by variable i with the value 1, the statement is true if i indeed is equal to 1, else the statement is false. Whereas the expression βif(i&1)β does a logical βANDβ operation with i and 1(2^0). We know that logical βandβ evaluates to true if both the operands turn out to be true. Here one operand is β1β and the other is i. If i is not zero then the expression (i&1) evaluates to be true. If i is zero then the expression evaluates to be false.
-
The statement βi==1β evaluates to true if and only if the value of the variable βiβ is equal to β1β.
-
The statement βi&1β evaluates to true if and only if the βlast bit in the binary form the variable βiβ is equal to β1ββ i.e., βiβ is an odd number. This is because the binary form of β1β is 000β¦001 and let us assume that βiβ has n bits and the binary form of the number βiβ be βa1a2a3β¦anβ. As the (n-1) most siginificant bits of β1β are '0βs the bitwise βANDβ would return 0βs in all those positions and now we have two cases for the least significant bit.
CASE 1: LSB = 0. IF LSB(i) == 0 then the bitwise βANDβ would return 0 even in the last bit and hence the statement evaluates to βfalseβ.
CASE 2: LSB = 1. IF LSB(i) == 1 then the bitwise βANDβ would return 1 in the last bit and hence the statement evaluates to βtrueβ.
Simply, the statement βi&1β evaluates to βtrueβ if βiβ is and odd number else it returns βfalseβ.
Thank you.
I am sorry, your explanation for the second statement is wrong. It will return truw only if the integer βiβ is an odd number, otherwise itβll return false.
Thank you.
& is bitwise AND not logical AND.
-
i == 1 is true if value of i is 1
-
i&1 is true if i is odd, since this involves bit operation, it is slightly faster than i%2==1 checking, although you might not notice any time difference in submissions using one in the place of another.
The most used bit operation are
-
<< (left shift): where the multiplier is in the powers of 2. Example 16 * 8 is equivalent to 16 << 3 (as 8 = 23)
-
(right shift): where the divisor is in the powers of 2. Example 16 / 8 is equivalent to 16 >> 3
If you are required to find a floor value after multiplication/division where the multiplier/divisor is in the powers of 2. Using the above approach you directly get the desired value, no need to use the floor() function then casting it with int to get the result after using the multiplication/division operator