Single Number
题目描述:
Given an array of integers, every element appears twice except for one. Find that single one.
题目思路:
找出给定数组中只出现一次的元素,别的元素都出现过两次。
使用异或运算,两个相同的数做异或运算等于0,0和非0的数做异或运算等于这个数。
题目代码:
class Solution {
public:
int singleNumber(vector<int>& nums) {
int ans = 0;
for(int num : nums) ans ^= num;
return ans;
}
};