You can check if a number is even or odd in many different ways, including through the use of bitwise operators.
Example 1:
Example 2:
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:
0
as their least significant bit in binary form.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:
&
) with the given number and 1
.1
, then the number is an odd number.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
RELATED TAGS
CONTRIBUTOR
View all Courses