How to check if Number is Odd or Even without using % operator

This is a very tricky question. The answer is to use bitwise operation.
We can use the & operation with the number to check this.

Below is the code.

System.out.println((a & 1) == 0 ?  "EVEN" : "ODD" );
Example:
number = 5 (binary is 101)
Binary: “101 & 1” will be 001, so false.
Output:ODD

number = 4 (binary is 100)
Binary: “100 & 1” will be 000, so true.
Output:EVEN
SHARE

    Blogger Comment
    Facebook Comment

0 comments :

Post a Comment