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

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

    max: // Will put MAX(a,b) into a

    a -= b;
    a &= (~a) >> 31;
    a += b;
    

    And:

    int a, b;

    min: // Will put MIN(a,b) into a

    a -= b;
    a &= a >> 31;
    a += b;
    

    from here.

提交回复
热议问题