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

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

    http://www.graphics.stanford.edu/~seander/bithacks.html#IntegerMinOrMax

    r = x - ((x - y) & -(x < y)); // max(x, y)
    

    You can have fun with arithmetically shifting (x - y) to saturate the sign bit, but this is usually enough. Or you can test the high bit, always fun.

提交回复
热议问题