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

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

提交回复
热议问题