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 ;
}
|
Python3
def invert(x):
if (x = = 1 ):
return 2
else :
return 1
|
C#
static int invert( int x)
{
if (x == 1)
return 2;
else
return 1;
}
|
Javascript
function invert(x)
{
if (x === 1)
return 2;
else
return 1;
}
|
C++
int invert( int x) {
if (x == 1) {
return 2;
}
else {
return 1;
}
}
|
Another solution is to use subtraction
C
int invertSub( int x)
{
return (3-x);
}
|
Java
static int invertSub( int x)
{
return ( 3 -x);
}
|
Python3
def invertSub(x):
return ( 3 - x)
|
C#
static int invertSub( int x)
{
return (3-x);
}
|
Javascript
function invertSub(int x)
{
return (3-x);
}
|
C++
int invertSub( int x) {
return (3 - x);
}
|
We can also use bitwise xor operator.
C
int invertXOR( int x)
{
return (x ^ 1 ^ 2);
}
|
Java
import java.util.*;
class GFG
{
static int invertXOR( int x)
{
return (x ^ 1 ^ 2 );
}
}
|
Python3
def invertXOR(x):
return x ^ 1 ^ 2
|
C#
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));
}
}
|
Javascript
function invertXOR(x)
{
return (x ^ 1 ^ 2);
}
|
C++
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
Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!