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;
}
static int invert(int x)
{
if (x == 1) return 2;
else return 1;
}
// This code is contributed by rishavmahato348.
def invert(x):
if (x == 1):
return 2
else:
return 1
# This code is contributed by rishavmahato348.
static int invert(int x)
{
if (x == 1)
return 2;
else
return 1;
}
// This code is contributed by rishavmahato348.
function invert(x)
{
if (x === 1)
return 2;
else
return 1;
}
// This code is contributed by subham348.
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);
}
static int invertSub(int x)
{
return (3-x);
}
// This code is contributed by shivanisinghss2110
def invertSub(x):
return (3-x)
# this code is contributed by shivanisinghss2110
static int invertSub(int x)
{
return (3-x);
}
// This code is contributed by subham348.
function invertSub(int x)
{
return (3-x);
}
// This code is contributed by shivanisinghss2110
int invertSub(int x) {
return (3 - x);
}
We can also use bitwise xor operator.
int invertXOR(int x)
{
return (x ^ 1 ^ 2);
}
// JAVA program of the above approach
import java.util.*;
class GFG
{
static int invertXOR(int x)
{
return (x ^ 1 ^ 2);
}
// This code is contributed by sanjoy_62.
}
# 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# program of the 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 program of the above approach
function invertXOR(x)
{
return (x ^ 1 ^ 2);
}
//This code is contributed by phasing17
int invertXOR(int x) {
return (x ^ 1 ^ 2);
}