【LeetCode从0单刷】Single Number

【LeetCode从零单刷】Single Number

没错我就是伍声2009的粉丝,从今天起,模仿《从零单排》系列,菜鸡单刷LeetCode!

题目:

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

解答:

其实就是找不同。这题需要一个比较trick的思路:位运算

试想,任何两个相同的数,进行异或操作答案是啥?是0. 4^8^4^8 = 0. 中间相隔N位也是如此。

0与任何数进行异或操作,答案是啥?是不是这个数自身。

class Solution {
public:
    int singleNumber(int A[], int n) {
        int sum = A[0];
        for(int i = 1; i<n; i++)
            sum = sum ^ A[i];
        return sum;
    }
};