Question

I want to write a function that gets a number X and if X=5 it returns 7 , if X=7 it return 5 otherwise, return something else. There is the trivial way - to use "if" blocks Another way - to use a map (5 mapped to 7, 7 mapped to 5) Third way - to write the matching linear mathematical equation BUT I'm looking for the 4th way of doing it (again - without using "if" blocks at all).

It feels like I need to use bit operation but I'm not dominant in this area so I need help.

Any ideas?

Thanks!

Was it helpful?

Solution

int fun(int p)
{
    return p^2;
}

OTHER TIPS

As well as the obvious bitwise XOR solution, you can also exploit the fact that a boolean expression returns 1 or 0, e.g.

int f(int x)
{
    return (x == 5) * 7 + (x == 7) * 5;
}

and there are other simple arithmetic methods, e.g.

int f(int x)
{
    return 12 - x;
}

I hope this is no homework I do for you:

int mysteriousFunction( int x ) {
    return (x ^ 2);
}

if input range is bounded and small, use input as index into a lookup table of results...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top