这一题是我之前找Java工作时的笔试题,比较有代表性,拿出来和大家分享。
package com.dylan.practice.interview;
/**
* 交换2个整形变量的几种方式
*
* @author xusucheng
* @create 2018-02-26
**/
public class ExchangeTwoVariable {
public static void main(String[] args) {
exchangeByThirdVar();
exchangeByPlusMinus();
exchangeByXOR();
}
//1.借助临时变量
private static void exchangeByThirdVar() {
int a = 1, b = 2, tmp;
tmp = a;
a = b;
b = tmp;
System.out.println("a=" + a + " b=" + b);
}
//2.不借助第三变量,通过加减方式
private static void exchangeByPlusMinus() {
int a = 1, b = 2;
a = a + b;
b = a - b;
a = a - b;
System.out.println("a=" + a + " b=" + b);
}
//3.通过异或运算
/*
异或运算 ^ 规则:不同为1
System.out.println( 1 ^ 2);
* 1二进制 0001
* 2二进制 0010
* ----------
* 0011 == 3
*
*
*/
private static void exchangeByXOR() {
int a = 1, b = 2;
a = a ^ b;
b = a ^ b; //1
a = a ^ b; //2
System.out.println("a=" + a + " b=" + b);
}
}
输出:
a=2 b=1a=2 b=1a=2 b=1