Given an array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
题意是说给你一个数组,只有一个数是出现一次的,其余数都出现两次,让你输入出现一次的数。
异或大法:相同为0,相反为原数
例如:a=1,b=1,c=9
d=a^b^c=9
我的代码:
class Solution {
public:
int singleNumber(vector<int>& nums) {
int res=0;
for(int i=0;i<nums.size();i++)
res^=nums[i];
return res;
}
};