有两个变量a、b,不用"if","

作者: 关玮琳linSir | 来源:发表于2017-02-10 23:33 被阅读127次

方法一:利用位运算,移位后,返回的就是其符号位

public static void main(String[] args) {
        int a = 8;
        int b = 50;
        int[] c = { a, b };
        int d = a - b;
        d = d >> 31;
        d = d * -1;
        System.out.println(c[d]);
    }

结果:

50

方法二:说一下啊,我不是很鼓励用,因为有点投机取巧的成分,看着是没用判断,但是内部是用了的

public static void main(String[] args) {
        int a = 7;
        int b = 3;
        int max = ((a + b) + Math.abs(a - b)) >> 1;
        System.out.println(max);

    }

结果:

7

相关文章

网友评论

    本文标题:有两个变量a、b,不用"if","

    本文链接:https://www.haomeiwen.com/subject/zepnittx.html