How do I programmatically return the max of two integers without using any comparison operators and without using if, else, etc?

后端 未结 10 2097
一生所求
一生所求 2020-12-09 10:35

How do I programmatically return the maximum of two integers without using any comparison operators and without using if, else, etc?

10条回答
  •  有刺的猬
    2020-12-09 11:18

    return (a > b ? a : b);

    or

    int max(int a, int b)
    {
            int x = (a - b) >> 31;
            int y = ~x;
            return (y & a) | (x & b); 
    }
    

提交回复
热议问题