Find maximum of three number in C without using conditional statement and ternary operator

前端 未结 13 1940
日久生厌
日久生厌 2020-11-29 22:25

I have to find maximum of three number provided by user but with some restrictions. Its not allowed to use any conditional statement. I tried using ternary operator like bel

13条回答
  •  粉色の甜心
    2020-11-29 23:15

    Boolean valued operators (including <, &&, etc) typically translate to conditional operations at the machine code level, so don't fulfill the spirit of the challenge. Here's a solution that any reasonable compiler would translate to only arithmetic instructions with no conditional jumps (assuming long has more bits than int and that long is 64 bits). The idea is that "m" captures and replicates the sign bit of b - a, so m is either all 1 bits (if a > b) or all zero bits (if a <= b). Note that long is used to avoid overflow. If for some reason you know that b - a doesn't over/under-flow, then the use of long isn't needed.

    int max(int a, int b)
    {
        long d = (long)b - (long)a;
        int m = (int)(d >> 63);
        return a & m | b & ~m;
    }
    
    int max(int a, int b, int c)
    {
        long d;
        int m;
        d = (long)b - (long)a;
        m = (int)(d >> 63);
        a = a & m | b & ~m;
        d = (long)c - (long)a;
        m = (int)(d >> 63);
        return a & m | c & ~m;
    }
    

提交回复
热议问题