Pages

Find odd even using bitwise operator

 As we have already seen in the previous post to swap two numbers without using the third variable and using the bitwise operator.πŸ‘‡

https://www.javaoneworld.com/2020/03/swap-two-numbers-using-bitwise-operator.html

 As I already mentioned that bitwise operators are always computational fast than any mathematical operators.



Why bitwise operators are computational fast than Mathematical operators πŸ‘ˆ

so using a bitwise operator instead of a mathematical operator is always a good approach.

Here we are using & operator to find that 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");
}
    }
}



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.

if we & 1 in any binary number it will result ---

1    --- if the given number's last bit will 1 (means number is odd)

0    --- if the given number's last bit will 0 (means number is even)
   

7  -- odd

       111
&       1
--------------                            
      001

4  -- even

       100
&       1
--------------                                  
      000

   
***********************
***********************
***********************

Happy Coding !!!!!!!!!!!πŸ‘πŸ‘πŸ‘πŸ‘πŸ‘

follow us on Instagram @javaoneworld

another must-read blog !!!!!!!!!!!!!!πŸ‘‡πŸ‘‡πŸ‘‡πŸ‘‡πŸ‘‡







Android Interview Question For Senior Android Developer




1 comment: