problem:
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?
thinking:
(1)考察位运算,C/C++的异或运算符为 ^
0^a=a;
a^a=0;
a^b=b^a;
(2)这道题的解法就出来了:n个数的异或结果就是待求数
code:
class Solution { public: int singleNumber(vector<int>& nums) { int n=nums.size(); int ret=nums[0]; for(int i=1;i<n;i++) ret^=nums[i]; return ret; } };
原文地址:http://blog.csdn.net/hustyangju/article/details/45367881