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

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

    I think I've got it.

    int data[2] = {a,b};
    int c = a - b;
    return data[(int)((c & 0x80000000) >> 31)];
    

    Would this not work? Basically, you take the difference of the two, and then return one or the other based on the sign bit. (This is how the processor does greater than or less than anyway.) So if the sign bit is 0, return a, since a is greater than or equal to b. If the sign bit is 1, return b, because subtracting b from a caused the result to go negative, indicating that b was greater than a. Just make sure that your ints are 32bits signed.

提交回复
热议问题