Given a non-empty array of integers, every element appears twice except for one. Find that single one.
获取数组中只出现一次的数,可以使用异或,0和任何数异或都是那个数本身,任意两个相同的数异或都是0。因此将数组中的所有的数异或就是只出现一次的数。
class Solution {
public:
int singleNumber(vector<int>& nums) {
int res = 0;
for(auto item : nums){
res ^= item;
}
return res;
}
};