public class CleverSwap{
public static void main(String[] args){
int x = 1984;
int y = 2001;
x ^= y ^=x ^= y;
System.out.println("x= " + x + "; y = " + y);
}
}
Solution:
显示:x = 0; y = 1984;
要使用中间变量
TID:
Swap variables without a temporary - Don't do this;
operands of operators are evaluated from left to right;
Do not assign to the same variable more than once in a single expression;
avoid clever programming tricks;
Correctly:
int tmp1 = x;
int tmp2 = y;
int tmp3 = x^y;
x = tmp3;
y = tmp2 ^ tmp3;
x = tmp1 ^ y;