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”.
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
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.
& is bitwise AND not logical AND.