Skip to content
Related Articles

Related Articles

Improve Article

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

  • Difficulty Level : Easy
  • Last Updated : 20 May, 2017

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.

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

Another solution is to use subtraction

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

We can also use bitwise xor operator.

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

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

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

My Personal Notes arrow_drop_up
Recommended Articles
Page :