Write a function that returns 2 for input 1 and returns 1 for 2

Write a function which returns 1 that 2 is passed and return 2 when 1 is passed.

Source: Adobe Interview Experience | Set 19 (For MTS)

A simple solution is to compare the passed value with 1 and 2.

filter_none

edit
close

play_arrow

link
brightness_4
code

int invert(int x)
{
   if (x == 1) return 2;
   else return 1;
}

chevron_right


Another solution is to use subtraction

filter_none

edit
close

play_arrow

link
brightness_4
code

int invertSub(int x)
{
   return (3-x);
}

chevron_right


We can also use bitwise xor operator.

filter_none

edit
close

play_arrow

link
brightness_4
code

int invertXOR(int x)
{
   return (x ^ 1 ^ 2);
}

chevron_right


This article is contributed by Anuj. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above



My Personal Notes arrow_drop_up


Article Tags :
Practice Tags :


1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.