In this post we will talk and learn How would you check if a number is even or odd using bit wise operator in Java? using an example.
If you look carefully for all Odd numbers rightmost bit is always 1 in binary representation.
1 2 3 4 |
if((number & 1) ==0) System.out.println(number +" is an even number"); else System.out.println(number +" is an odd number"); |
Notes
We should prefer Bitwise operator for checking even or odd because the traditional way of checking even by n % 2 ==0 is compassionately expensive compared to Bitwise & operator (Big O(1) time complexity)
Let’s try to understand above concept using couple of examples.
- Check a number is odd or even using modulus operator
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 |
package com.kkjavatutorials.client; import java.util.Scanner; /** * @author KK JavaTutorials *Check a number is odd or even using modulus operator */ public class CheckOddEvenTest_1 { public static void main(String[] args) { Scanner scanner = null; int number; try { scanner = new Scanner(System.in); System.out.print("Enter number:"); number = scanner.nextInt(); if(number%2 ==0) System.out.println(number +" is an even number"); else System.out.println(number +" is an odd number"); } catch (Exception e) { e.printStackTrace(); } } } |
2. Check a number is odd or even without modulus(using bitwise) operator
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 |
package com.kkjavatutorials.client; import java.util.Scanner; /** * @author KK JavaTutorials *Check a number is odd or even without modulus(using bitwise) operator */ public class CheckOddEvenTest_2 { public static void main(String[] args) { Scanner scanner = null; int number; try { scanner = new Scanner(System.in); System.out.print("Enter number:"); number = scanner.nextInt(); if((number & 1) ==0) System.out.println(number +" is an even number"); else System.out.println(number +" is an odd number"); } catch (Exception e) { e.printStackTrace(); } } } |
Sample input/output of above programs:
1 2 3 4 5 6 7 8 |
Enter number:12 12 is an even number Enter number:13 13 is an odd number Enter number:1 1 is an odd number |
That’s all about How would you check if a number is even or odd using bit wise operator in Java?
If you have any feedback or suggestion please feel free to drop in blow comment box.