QUESTION - what is the difference between if(i==1) and if (i&1)

IT IS A CONCEPTUAL QUESTION -> plz answer in detail

4 Likes

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.

  1. The statement β€œi==1” evaluates to true if and only if the value of the variable β€œi” is equal to β€œ1”.

  2. 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.

2 Likes

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

:wink: