December 18, 2006 7:20pm CST
I wanna swap the values of two variables: A and B. How can I do it without using a third variable? Please give me a good algorithm. Thanks!
• United States
19 Dec 06
This is a well-known puzzle. The solution is to use the 'exclusive-or' operator; in C, C++, java and Perl (at least, and probably other languages I'll not stop to verify now), exclusive-or is coded with the caret, '^'. To swap the values of A and B, code the following three statements: A=A^B; B=A^B; A=A^B; Note, however, that this only works when A and B are integers of the same length. It will not work when A and B are different sizes or when they are floating-point values.