一 不引入新变量交换两个变量的值
1 通过加法
不好的地方在于如果a值足够大,以至于加一个数就溢出,比如int型在常见的32位或64位机器占4个字节,则最大的有符号整数是2^31-1,最小的是-2^31
C++版本:
#include <iostream> using namespace std; int main() { // your code goes here int a,b; a=5; b=8; a=a+b; b=a-b; a=a-b; cout<<"a:"<<a<<endl; cout<<"b:"<<b<<endl; return 0; }
python版本:
# your code goes here a=5 b=8 a=a+b b=a-b a=a-b print "a:",a,"b:",b
2 通过减法
C++版本:
#include <iostream>
using namespace std;
int main() {
// your code goes here
int a,b;
a=5;
b=8;
a=a-b;
b=a+b;
a=b-a;
cout<<"a:"<<a<<endl;
cout<<"b:"<<b<<endl;
return 0;
}
python版本:
# your code goes here
a=5
b=8
a=a-b
b=a+b
a=b-a
print "a:",a,"b:",b
3 通过指针地址操作
原理:异或运算的交换律和结合律
C++版本:
#include <iostream> using namespace std; int main() { // your code goes here int a,b; a=5; b=8; a=a^b; b=a^b; a=a^b; cout<<"a:"<<a<<endl; cout<<"b:"<<b<<endl; return 0; }
python版本:
# your code goes here a=5 b=8 a=a^b b=a^b a=a^b print "a:",a,"b:",b
3 通过异或
原理:异或运算的交换律和结合律
C++版本:
#include <iostream>
using namespace std;
int main() {
// your code goes here
int a,b;
a=5;
b=8;
a=a^b;
b=a^b;
a=a^b;
cout<<"a:"<<a<<endl;
cout<<"b:"<<b<<endl;
return 0;
}
python版本:
# your code goes here
a=5
b=8
a=a^b
b=a^b
a=a^b
print "a:",a,"b:",b