theboyaply
theboyaply
发布于 2020-01-03 / 855 阅读
0
0

java基础四(使用异或运算交换两变量值)

        // 交换m和n的值
        int m = 10;
        int n = 7;
        System.out.println("m:" + m + ", n: " + n);
        // 方法一,缺点,需要新增临时变量,消耗内存
        int temp = m;
        m = n;
        n = temp;
        System.out.println("m:" + m + ", n: " + n);

        // 方法二,缺点,当m和n较大时,m+n可能会溢出,导致精度损失
        m = m + n;
        n = m - n;
        m = m - n;
        System.out.println("m:" + m + ", n: " + n);

        // 方法三,没有方法一和二的缺点
        m = m ^ n;
        n = m ^ n;
        m = m ^ n;
        System.out.println("m:" + m + ", n: " + n);


评论