【LeetCode】136. Single Number

时间:2022-06-23 08:55:01

题目:

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?

提示:

此题的主要是利用异或运算(xor)的特性:不同的输出1,相同的输出0。

例如:101 ^ 101 = 000, 111 ^ 000 = 111。

代码:

class Solution {
public:
int singleNumber(vector<int>& nums) {
vector<int>::iterator it;
int result = ;
for (it = nums.begin(); it < nums.end(); ++it) {
result ^= (*it);
}
return result;
}
};