Search code examples
logical-operators

Combining of logical conditions in IF statement


I just notice the if condition below:

//1
if ((i >= 0) != (j >= 0))
 return false;

is just a short way for:

//2
if((i>=0 && j < 0) || (i < 0 && j >=0))
 return false;

Going from 1. to 2. takes some time to figure out, but how do we deduce the logic to go from 2. to 1.?


Solution

  • If you have any two boolean statements A and B then A != B means that they are different. I.e. either A is true and B is false, or A is false and B is true. This goes also the other way if A is true and B is false, or A is false and B is true, then A does not equal B.

    In other words (A != B) = ((A && !B) || (!A && B)). Therefore, statement 1 and 2 are the same

    If you feel my argumentation is imprecise, you can use truth tables to proof it rigorous mathematically:

    A B A!=B (A && !B) (!A && B) (A && !B) || (!A && B))
    true true false false false false
    true false true true false true
    false true true false true true
    false false false false false false