Even Odd GeeksForGeeks

 Problem Link:


https://practice.geeksforgeeks.org/problems/even-odd/1#


Solution:


class Solution{

    public void evenOdd(int a, int b){

        int a1=a&1;

        if(a1==1){

            System.out.println(b);

            System.out.println(a);

        }

        else{

             System.out.println(a);

            System.out.println(b);

        }

    }

}



TIME:O(1)[Geeks For Geeks Time: 0.1/1.3]

SPACE:O(1)


Approach:

Since in question only they have asked to print even number before than odd number, so it is a guarantee that among two numbers they provide one will be even one will be odd. 

So if we check for one number only the other number will be reverse of that.

That's why here we checked for number a and if it is even then b will be odd and vice versa.

For a to be even, it should return output to 0 once masked with 1.

(Masking approach:

Actually, this masking approach deals with the bits. We can do masking through and, or, xor operation. 

example: 

if the number is 5 then binary will be 101 and if we do and with 1 (001) then the last bit will be 1.[odd]

if the number is 6 then binary will be 110 and if we do and with 1 (001) then the last bit will be 0.[even]


So it's an easy way of finding whether a number is odd or even just by simply taking bits and with 1.)


int a1=a&1;[masking a with 1 and storing result in a1.]

if(a1==0) ie a is even so b will be odd.

if(a1==1) ie a is odd so a will be even,.

Hence we print even numbers first then odd numbers first.


Thanks For Reading😇.

"Share Further To Increase Knowledge Treasure.😊"


Comments

Popular posts from this blog

Solutions Of Practice Questions Dated 01-06-2022

CODEFORCES SPY DETECTED ROUND 713

Maximum Winning Score Geeks For Geeks