'Difference between !(n & 1) and n & 1 == 0 in C++
For some reason in C++, the expressions if(!(n & 1))
and if(n & 1 == 0)
seem to not be equivalent.
Can someone please explain why this happens?
Solution 1:[1]
if(!(n & 1))
will evaluate totrue
if the least significant bit ofn
is1
.if(n & 1 == 0)
is equivalent toif(n & (1 == 0))
, which will becomeif (n & 0)
, which is alwaysfalse
.
Check out the operator precedence table, you will see that ==
precedes &
.
Solution 2:[2]
Because of operator precedence. n & 1 == 0
is parsed as n & (1 == 0)
, not (n & 1) == 0
.
Solution 3:[3]
Normally (n&1), if we assume n is integer example 2 then first it will convert in 32bit integer so 2= 00000000000000000000000000000010 and in the other hand 1=00000000000000000000000000000001 now we apply "&" operator which return us 0 (you can simply do a Binary Multiplication). Now if we take an example as 3=00000000000000000000000000000011, here output will be 1.
So basically we use n&1 to check the last bit is set or not. (you can also say the number is even or odd)
Now in your question, 1.if(!(n & 1)) : here first n&1 will perform and what ever the value returned it will Logical Not.
- if(n & 1 == 0) : for this here we need to know that "==" execute first then "&" will execute because of operator precedence. so here (1==0) return a 0 bcz both integers are not equal and then we will do n&0 and we all no if we multiply anything with 0, then it will return 0, so it will return always false.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Aziz |
Solution 2 | Joseph Sible-Reinstate Monica |
Solution 3 | Rounak Mukherjee |