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

前端 未结 13 2003
日久生厌
日久生厌 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 22:55

    No conditionals. Only a cast to uint. Perfect solution.

    int abs (a) { return (int)((unsigned int)a); }
    int max (a, b) { return (a + b + abs(a - b)) / 2; }
    int min (a, b) { return (a + b - abs(a - b)) / 2; }
    
    
    void sort (int & a, int & b, int & c)
    {
       int max = max(max(a,b), c);
       int min = min(min(a,b), c);
       int middle = middle = a + b + c - max - min;
       a = max;
       b = middle;
       c = min;
    }
    

提交回复
热议问题