We read in math Odd and Even numbers that is Odd numbers are whole numbers that cannot be divided exactly into pairs and Any number that can be exactly divided by 2 is called as an even number.
Example :
Odd Number – 1, 3, 5, 7, 9, 11, 13, 15……
Even Number – 2, 4, 6, 8, 10, 12, 14, 16…..
Before going to solution first lets see what is bitwise operator.
Bitwise operators are used for manipulating a data at the bit level that is 0(zero) and 1(one).
Basically there are two methods in bitwise operator that is “Bitwise AND(&) operator” and “Bitwise OR(|) operator.
Here i’m going to use “Bitwise AND(&) operator”.
/* Bitwise AND (&) operator */
0 + 0 = 0
0 + 1 = 0
1 + 0 = 0
1 + 1 = 1
In the above code example we see how bitwise & operator works.
Now come to the question by using of bitwise & operator how we determine odd or even number,so let’s see below code –
<?php
$n = "11"; // user input
// 11 in binary = 1011
// 1 in binary = 0001
// solving by Bitwise AND operator
// 1011 & 0001 = 0001 = 1
if($n & 1 == 1){
echo "Odd";
}
else{
echo "Even";
}