实现方法
#include <iostream>
using namespace std;
void bit_swap(int &a, int &b){
a = a^b;
b = a^b;
a = a^b;
}
int main(){
int a=1, b=89;
bit_swap(a, b);
cout << a << ' ' << b << endl;
return 0;
}
实现原理
^符号为C/C++中的异或运算符,相同为假,相异为真,上述例子中我们定义了a = 1,b = 89,用二进制表示为:
a = 0000001 = 1
b = 1011001 = 64 + 16 + 8 + 1
a = a^b = 1011000
b = a^b = 0000001
a = a^b = 1011001