leetcode-136-single number

Problem Description:

Given an array of integers, every element appears twice except for one. Find that single one.

题目大意:

给定一个数组,其中除了某一个数字以外其他数字都出现过两次,找出这个数字。

Solutions:

这道题方法有许多,这里本文介绍最简单的一种,使用位运算,一个数字a^b^b以后仍然为它本身。这样,把整个数组^一次即可。

Code in C++:

class Solution {
    public:
        int singleNumber(vector<int>& nums) {
            int res=0;
            for(int i=0;i<nums.size();i++)
                res^=nums[i];

            return res;

        }
};