Check whether number is even or odd

Solution 1:

You can use the modulus operator, but that can be slow. If it's an integer, you can do:

if ( (x & 1) == 0 ) { even... } else { odd... }

This is because the low bit will always be set on an odd number.

Solution 2:

if ((x % 2) == 0) {
   // even
} else {
   // odd
}

Solution 3:

If the remainder when you divide by 2 is 0, it's even. % is the operator to get a remainder.

Solution 4:

The remainder operator, %, will give you the remainder after dividing by a number.

So n % 2 == 0 will be true if n is even and false if n is odd.