int fun(int p)
{
return p^2;
}
C code - a way to convert 5 to 7 and 7 to 5 without "if"
-
13-06-2023 - |
题
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!
解决方案
其他提示
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...