How to use bitwise operations to check if a number is even or odd

You can check if a number is even or odd in many different ways, including through the use of bitwise operators.

Example 1:

  • Given number = 24
  • Output = even

Example 2:

  • Given number = 13
  • Output = odd

Algorithm

First, let’s convert the following numbers to binary representation.

Number Binary representation
24 “11000
22 “10110
13 “1101
7 “111

When we observe the least significant bit (the rightmost bit), we find the following observations:

  • Even numbers have 0 as their least significant bit in binary form.
  • Odd numbers have 1 as their least significant bit in binary form.

Hence, one algorithm to find if a number is even or odd using bitwise operations is as follows:

  1. Do a bitwise AND (&) with the given number and 1.
  2. If the result of the above step is 1, then the number is an odd number.
  3. Otherwise, the number is an even number.

Code

The code to check if a number is odd or even using & is provided below.

import java.util.Scanner;
public class Main{
private static void OddOrEven(int n){
if((n & 1) == 1) System.out.println("The number " + n + " is an odd number");
else System.out.println("The number " + n + " is an even number");
}
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
int number = scanner.nextInt();
OddOrEven(number);
}
}

Enter the input below

Free Resources