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

后端 未结 10 2175
一生所求
一生所求 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: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.

提交回复
热议问题