三种方式交换两个变量的值

1.使用中间变量法交换两个变量的值

public class exchangeValue {

    public static void main(String[] args) {
        //定义变量a,b
        int a = 10,b = 5;
        
        //使用中间变量法交换两个变量的值
        int t;
        System.out.println("交换前:a="+a+"\tb="+b);
        t = a; a = b; b = t;
        System.out.println("交换后:a="+a+"\tb="+b);
    }
}

2.使用加减法交换两个变量的值

public class exchangeValue {

    public static void main(String[] args) {
        //定义变量a,b
        int a = 10,b = 5;
        
        //使用加减法交换两个变量的值
        System.out.println("交换前:a="+a+"\tb="+b);
        a = a + b;b = a - b;a = a - b; 
        System.out.println("交换后:a="+a+"\tb="+b);
    }
}

3.使用异或交换两个变量的值

public class exchangeValue {

    public static void main(String[] args) {
        //定义变量a,b
        int a = 10,b = 5;
        
        //使用加减法交换两个变量的值
        System.out.println("交换前:a="+a+"\tb="+b);
        a = a ^ b; b = b ^ a; a = a ^ b;
        System.out.println("交换后:a="+a+"\tb="+b);
        
        //异或的特点,当一个数异或某一个数两次;其值不变。
        System.out.println(a ^ b ^ b);
    }
}
Last modification:March 17th, 2019 at 01:33 pm
If you think my article is useful to you, please feel free to appreciate

Leave a Comment