Exchange two numbers without another variable

来源:互联网 发布:淘宝货到付款钱给谁 编辑:程序博客网 时间:2024/06/09 20:13

Usually  we exchange two numbers we need another temp variable ,it is possible to exchange without the temp.We can use bit  compute.

Two variables A =1,B=2;

now do these:

A=A^B;//A=0001^0010=0011;

B=B^A;//B=0010^0011=0001(A)

As the same:

A=B^A;

# include <iostream>using namespace std;int main(){int a=1;int b=2;cout<<"Before exchange:"<<"a="<<a<<" , b="<<b<<endl;a=a^b;b=a^b;a=a^b;    cout<<"After  exchange:"<<"a="<<a<<" , b="<<b<<endl;}