# 1、算法思路

（1）利用中间变量交换数据
（2）两个数先进行求和，然后相减进行数据交换
（3）利用位运算的方式进行数据交换(一个数异或同一个数两次，结果还是那个数)

# 2、具体代码

package com.peter.algorithm.other;

import org.junit.Test;

public class VariablExchange {
@Test
public void test() {
swapByTempVariable();
swapBySum();
swapByBitOperation();
}

//利用中间变量交换数据
public static void swapByTempVariable() {
int a = 3, b = 5;
System.out.println("swapByTempVariable before exchange! a:" + a + " b:" + b);
int temp = a;
a = b;
b = temp;
System.out.println("swapByTempVariable after exchange! a:" + a + " b:" + b);
}

//两个数求和然后相减的方式进行数据交换
private static void swapBySum() {
int a = 3, b = 5;
System.out.println("swapBySum before exchange! a:" + a + " b:" + b);
a = a + b;
b = a - b;
a = a - b;
System.out.println("swapBySum after exchange! a:" + a + " b:" + b);
}

//利用位运算的方式进行数据的交换(一个数异或同一个数两次，结果还是那个数)
private static void swapByBitOperation() {
int a = 3, b = 5;
System.out.println("swapByBitOperation before exchange! a:" + a + " b:" + b);
a = a ^ b;
b = a ^ b;
a = a ^ b;
System.out.println("swapByBitOperation after exchange! a:" + a + " b:" + b);
}
}