Find even/odd number using bitwise operator

Bitwise operators performs bit by bit operation on binary representation of integers. These operators acts upon the individual bits of their operands.

To find a number is even or odd we can simply apply the ‘&’ bitwise operator to the number an to  1.

Example :

First operand – >  x = 3; Binary representation of 3  is  011.

Second operand – > 1 ; Binary representation of 1  is  001.

operation : ( x & 1 ) – >  011 & 001 = 001

Since 001  = 1 , The number is odd.

Follow the java code below.


public class OddEven {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();

String res = ((n & 1) > 0)?"Odd":"Even";
System.out.println("Result -> " +res);
}
}

Input : 3

Output : Result is : Odd

 

 

 

Close Menu