扪心自问,不借助第三变量实现两个变量value的交换,你怎么做?
3
2
1
看两种思路:
一.联想运算
不多说,试着去感受它的奇妙
#include<iostream>
using namespace std;
int main(){
int a = 3;
int b = 5;
a = a + b;
b = a - b;
a = a - b;
cout << a <<" "<< b << endl;
}
二.异或运算
想一下异或运算是怎么操作的
1^1=0;
1^0=1;
0^0=0;
于是乎:
0^0=0;
a^a=0;
0^a=a;
则a^a^b=b;
同时a^b^a=b;
而且b^a^a=b;
即^存在交换律
思路是不是出来了,上代码:
#include<iostream>
using namespace std;
int main(){
int a = 3;
int b = 5;
a = a ^ b;
b = a ^ b;
a = a ^ b;
cout << a << " " << b << endl;
}
-->题解来自于比特鹏哥<--
下一篇博文再度回味移位运算的地位
标签:面试题,运算,int,namespace,异或,逆天,include,cout From: https://blog.csdn.net/FENGCHEN____/article/details/139451343