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

后端 未结 10 2099
一生所求
一生所求 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); 
    }
    
    0 讨论(0)
  • 2020-12-09 11:18

    not as snazzy as the above... but...

    int getMax(int a, int b)
    {
        for(int i=0; (i<a) || (i<b); i++) { }
        return i;
    }
    
    0 讨论(0)
  • 2020-12-09 11:24

    In the math world:

    max(a+b) = ( (a+b) + |(a-b)| ) / 2
    min(a-b) = ( (a+b) - |(a-b)| ) / 2
    

    Apart from being mathematically correct it is not making assumptions about the bit size as shifting operations need to do.

    |x| stands for the absolute value of x.

    Comment:

    You are right, the absolute value was forgotten. This should be valid for all a, b positive or negative

    0 讨论(0)
  • 2020-12-09 11:27

    Since this is a puzzle, solution will be slightly convoluted:

    let greater x y = signum (1+signum (x-y))
    
    let max a b = (greater a b)*a + (greater b a)*b
    

    This is Haskell, but it will be the same in any other language. C/C# folks should use "sgn" (or "sign"?) instead of signum.

    Note that this will work on ints of arbitrary size and on reals as well.

    0 讨论(0)
提交回复
热议问题