DEV Community

loading...

Find odd even using Bitwise operator.

Amit Mishra
Curious coder, Coding by passion Coder by profession
・1 min read

Here we'll use & operator to find thae number is Odd or Even.

public class JavaOneWorld {
public static void main(String 
     args[]) {
     int x= 7;

   if((x&1)==0){
     System.out.println("even");
 }else{
    System.out.println("odd");
    }
   }
  }
Enter fullscreen mode Exit fullscreen mode

The idea behind using the & operator !!!!!

As we already know binary works only on 1 and 0.
and a number is either odd or even,
so if a number is even then the last bit of that number must be 0 and if odd then the last bit must be 1.

i.e.-

5 odd
101 last bit is 1.

4 even

100 last bit is 0.

so here we have to use this property to find out the odd/even

Deep dive in this post...

https://www.javaoneworld.com/2021/05/find-odd-even-using-bitwise-operator.html?m=1

Discussion (0)

Forem Open with the Forem app