Numbers can be Even or Odd, we call as Even when it is divided by 2 and remainder is 0, we call as Odd when it is divided by 2 and remainder is 1
Examples :
Input : 26 Output : Even Input : 27 Output : Odd
/**
* Function to find the given number is Even or Odd
*
* return string [ "Even", "Odd" ]
*/
function findEvenOrOdd( $num ) {
// Find even or add
// Return
// "Even" when the remainder is 0 after dividing by 2
// "Odd" when the remainder is 1 after diving by 2
return "Even";
}
1. Solution – Using array method. PHP is very special in arrays, so by using array it is simple to find if the given number is even or odd. It is done by declaring an array with the index of Even(0) and Odd(1) by using modulo operator Below program explains the above approach:
/**
* Function to find the given number is Even or Odd
* Return Even or Odd based on index of 0 or 1
*
* return string [ "Even", "Odd" ]
*/
function findEvenOrOdd( $num ) {
$result = [ 'Even', 'Odd' ][ $num % 2 ];
return $result;
}
echo findEvenOrOdd( 5 ); // Odd
Output :
Odd
Explanation : Declaring an array [ ‘Even’, ‘Odd’ ] with the position of 0 and 1, which specifies 0 as ‘Even’ and 1 as ‘Odd’. The $num variable modules 2 returns 0 or 1, so it will return the respective position. Which gives the result
Time Complexity : O(1)
2. Solution – Using bit operations Bit wise operator AND (‘&’) will return true when both the bits are true(1) else false(0). When we do bitwise AND with the given number, we will get 0 or 1 as bit, when it is 1, we can say it is an Odd number otherwise Even number.
/**
* Function to find the given number is Even or Odd
* Return Even or Odd based bitwise operations
*
* return string [ "Even", "Odd" ]
*/
function findEvenOrOdd( $num ) {
$numberOne = 1;
$operatedAnswer = $num & $numberOne;
$result = 'Even';
if( $operatedAnswer == 1 ){
$result = 'Odd';
} // else default value
return $result;
}
echo findEvenOrOdd( 28 ); // Even
Output :
Even
Explanation : Declaring variable with value as 1 in $numberOne. Then bitwise AND ‘&’ operator with the given number $num, so the result will be ‘1’ when it is odd number, 0 when it is an even number. Incase the last bit is ‘1’ and bitwise with ‘1’, so the result will be ‘1’, otherwise it will be ‘0’. So ‘1’ represents Odd and ‘0’ represents Even Bitwise AND ‘&’ table
| Input Bit | $numberOne Bit | Answer |
|---|---|---|
| 1 | 1 | 1 |
| 0 | 1 | 0 |
Time Complexity : O(1)