在交换两个变量的时候我们时常通过一个中间变量来实现两个值得互换。
在这里,我们实现整型变量在不通过中间变量的情况进行值得交换。
四则运算交换法:
int main()
{
int a = 1, b = 2;
cout << "交换前:" << endl;
cout << "a = " << a << "\t" << "b = " << b << endl;
//四则运算交换
a = a + b;
b = 2 * b - a;//b-a
a = (a + b) / 2;
b = a - b;
cout << "交换后:" << endl;
cout << "a = " << a << "\t" << "b = " << b << endl;
return 0;
}
异或运算法:
int main()
{
int a = 1, b = 2;
cout << "交换前:" << endl;
cout << "a = " << a << "\t" << "b = " << b << endl;
//异或运算
a = a^b;
b = a^b;
a = a^b;
cout << "交换后:" << endl;
cout << "a = " << a << "\t" << "b = " << b << endl;
<span style="white-space:pre"> </span>return 0;
}
其结果均可以交换成功,具体的大家看下源码慢慢理解了。