I tried some code to swap two integers in Java without using a 3rd variable, using XOR.
Here are the two swap functions I tried:
package lang.numeric;
public class SwapVarsDemo {
public static void main(String[] args) {
int a = 2984;
int b = 87593;
swapDemo1(a,b);
swapDemo2(a,b);
}
private static void swapDemo1(int a, int b) {
a^=b^=a^=b;
System.out.println("After swap: "+a+","+b);
}
private static void swapDemo2(int a, int b) {
a^=b;
b^=a;
a^=b;
System.out.println("After swap: "+a+","+b);
}
}
The output produced by this code was this:
After swap: 0,2984
After swap: 87593,2984
I am curious to know, why is this statement:
a^=b^=a^=b;
different from this one?
a^=b;
b^=a;
a^=b;
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…