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

7 Likes
• 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.
Thank you.

& is bitwise AND not logical AND.