Checking a number is Odd or Even is very simple. To determine the number is odd or even, one can use of modulus or division operator.
But what if, we have condition to check the number is odd or even without using Arithmetic operators?
It is very simple to check whether the number is odd or even, if we have knowledge of Bitwise operators.Using Bitwise And (&) Operator we can achieve the requirement easily.
Our logic of using Bitwise And (&) to find Odd or Even is , if "Number & 1 == 0" then the Number is Even else Odd.
Lets us see the program -
package com.mylogicalindian.oddeven;
public class OddOrEven {
public static void checkOddOrEven(int number){
if((number & 1) == 0){
System.out.println(number+" is Even");
}else{
System.out.println(number+" is Odd");
}
}
public static void main(String args[]){
checkOddOrEven(34);
checkOddOrEven(75);
}
}
Output -
34 is Even
75 is Odd
No comments:
Post a Comment