[LeetCode] Single Number

来源:互联网 发布:mac口红珊瑚色 编辑:程序博客网 时间:2024/06/12 01:31

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

Could you implement it without using extra memory?


Solution: 利用异或的可交换性!!!!!!!!!!!!!!

class Solution {public:    int singleNumber(int A[], int n) {        // Note: The Solution object is instantiated only once and is reused by each test case.        if(n==0)            return 0;                int result=A[0];        for(int i=1;i<n;i++)        {            result^=A[i];        }        return result;    }};