题目链接:
本题要求不能借助临时变量交换 \(a\) 和 \(b\) 的值,应想到借助异或运算的性质。本题亦是异或运算的一个经典应用。
a = a ^ b;//记a ^ b的值为c
b = b ^ a = b ^ (a ^ b) = a ^ (b ^ b) = a ^ 0 = a;
a = a ^ b = (a ^ b) ^ a = b ^ (a ^ a) = b;
即实现了两个数的交换。
以下是 \(AC\) 代码。
class Solution {
public:
vector<int> swapNumbers(vector<int>& numbers) {
vector<int> v;
int a = numbers[0], b = numbers[1];
a = a ^ b;
b = b ^ a;
a = a ^ b;
v.push_back(a), v.push_back(b);
return v;
}
};
标签:面试题,交换,back,16.01,异或,vector,numbers
From: https://www.cnblogs.com/pangyou3s/p/18100284