Hey there!
Welcome to ClearUrDoubt.com.
In this post, we will look at a Java program to find whether a number is even or odd without using modulus/division operator.
Without using the Modulus/division operator, this can be achieved by using “bitwise AND” operator.
I would recommend you to go through the below post before you continue with this.
2’s complement – Binary representation of Negative numbers in Java
Logic: When a number is applied bitwise AND(“&“) with 1, if the LSB of the result is zero then the given number is Even else it is Odd.
Here is the Java program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
package com.sample.clearurdoubt; import java.util.Scanner; public class OddEvenFinder { public static void main(String[] args) { System.out.println("Enter a number: "); Scanner input = new Scanner(System.in); int val = input.nextInt(); System.out.println(isEven(val) ? (val + " is an Even Number.") : (val + " is an Odd Number.")); input.close(); } private static boolean isEven(int val) { if( (val & 1) == 0) { return true; } else { return false; } } } |
Output:
Happy Learning :).
Please leave a reply in case of any queries.
Thanks a lot