java 不利用第三个变量的情况下将值互换

package com.zcj.eg001;

public class VarChange {
    public static void main(String[] args) {
        int a = 10;
        int b = 15;
        System.out.println(a+";"+b);
        
        int temp = a;
        a = b;
        b = temp;
        System.out.println(a+";"+b);
        
        //超出 int 的值会损失精度
        a = a + b;
        b = a - b;
        a = a - b;
        System.out.println(a+";"+b);
        
        //一个数异或同一个数两次,结果还是那个数,而且不会超出int范围
        a = a^b;
        b = a^b;
        a = a^b;
        System.out.println(a+";"+b);
        
        
    }

}

 

posted @ 2018-07-18 16:04  真某人  阅读(236)  评论(0编辑  收藏  举报