Topic: Do not use a temporary variable exchange values of two variables
Analysis: addition, subtraction, multiplication, or that (A B A == B), four methods are as follows:
//方法一:利用加法
int Swap3(int *x, int *y)
{
*x = *x + *y;//*x是二者和
*y = *x - *y;//*y是*x
*x = *x - *y;//*x是*y
}
//方法二:利用减法
int Swap1(int *x, int *y)
{
*x = *x - *y;//*x是二者差值
*y = *x + *y;//*x是*y
*x = *y - *x;//*y是*x
}
//方法三:利用乘法
int Swap4(int *x, int *y)
{
*x = (*x) * (*y);//*x是二者乘积
*y = *x / *y;//*y是*x
*x = *x / *y;//*x是*y
}
//方法四:利用除法
int Swap2(int *x, int *y)
{
*x = *x ^ *y;
*y = *x ^ *y;
*x = *x ^ *y;
}
//方法五:创建临时变量
int Swap5(int *x, int *y)
{
int tmp = *x;
*x = *y;
*y = tmp;
}