One of the classic interview questions is how to swap the values of two variables without using a third variable as a temporary storage space. Typically, this is done using a temporary variable as follows:
temp = a; a = b; b = temp;
However, this approach requires additional memory allocation and manipulation. An alternative solution is to use the XOR swap algorithm.
The XOR swap algorithm works by exploiting the exclusive OR (XOR) operation. The XOR operator has the property that a XOR a always returns 0, while a XOR b returns a if b is 0, and b if a is 0.
Using this property, we can swap the values of two variables x and y as follows:
// XOR swap function void xorSwap(int* x, int* y) { if (x != y) { //ensure that memory locations are different *x ^= *y; *y ^= *x; *x ^= *y; } }
Why it works:
XOR operations: We then perform the following XOR operations in sequence:
As a result of these operations, *x now contains the original value of *y, and *y contains the original value of *x.
Here is an example of how to use the XOR swap algorithm in C:
#include <stdio.h> int main() { int a = 10; int b = 15; printf("Before swap: a = %d, b = %d\n", a, b); xorSwap(&a, &b); printf("After swap: a = %d, b = %d\n", a, b); return 0; }
Output:
Before swap: a = 10, b = 15 After swap: a = 15, b = 10
While the XOR swap algorithm is efficient and eliminates the need for a third variable, it is not always the most optimal solution. In many cases, the compiler will optimize the code using the more traditional method with a temporary variable. Therefore, it is important to consider the specific requirements of your program before using the XOR swap algorithm.
The above is the detailed content of How to Swap Variable Values Without Using a Third Variable?. For more information, please follow other related articles on the PHP Chinese website!