Skip to content
Related Articles

Related Articles

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

Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 01 Jul, 2022
Improve Article
Save Article

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.
 

C




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

Java




static int invert(int x)
{
   if (x == 1) return 2;
   else return 1;
}
 
// This code is contributed by rishavmahato348.

Python3




def invert(x):
   if (x == 1):
      return 2
    else:
      return 1
 
    # This code is contributed by rishavmahato348.

C#




static int invert(int x)
{
    if (x == 1)
        return 2;
    else
        return 1;
}
 
// This code is contributed by rishavmahato348.

Javascript




function invert(x)
{
   if (x === 1)
           return 2;
   else
           return 1;
}
 
// This code is contributed by subham348.

Another solution is to use subtraction
 

C




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

Java




static int invertSub(int x)
{
   return (3-x);
}
 
// This code is contributed by shivanisinghss2110

Python3




def invertSub(x):
 
   return (3-x)
 
# this code is contributed by shivanisinghss2110

C#




static int invertSub(int x)
{
   return (3-x);
}
 
// This code is contributed by subham348.

Javascript




function invertSub(int x)
{
   return (3-x);
}
 
// This code is contributed by shivanisinghss2110

We can also use bitwise xor operator.
 

C




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

Java




// JAVA program of th above approach
import java.util.*;
class GFG
{
     
    static int invertXOR(int x)
    {
        return (x ^ 1 ^ 2);
    }
     
     // This code is contributed by sanjoy_62.
 
}

Python3




# Python3 program to implement the above approach
 
 
# This function returns 2 if x is 1
# and vice versa
def invertXOR(x):
    return x ^ 1 ^ 2
 
# This code is contributed by phasing17

C#




// C# program of th above approach
 
using System;
 
class GFG {
 
    static int invertXOR(int x) { return (x ^ 1 ^ 2); }
 
    public static void Main(string[] args)
    {
        Console.WriteLine(invertXOR(1));
        Console.WriteLine(invertXOR(2));
    }
}
 
// This code is contributed by phasing17

Javascript




// JavaScript program of th above approach
 
function invertXOR(x)
{
    return (x ^ 1 ^ 2);
}
     
 
//This code is contributed by phasing17

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
Related Articles

Start Your Coding Journey Now!