题目描述:
Given a non-empty 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?
Example 1:
Input: [2,2,1] Output: 1
Example 2:
Input: [4,1,2,1,2] Output: 4
解题思路:~:非运算,单目运算符1为0,0为1;
&:与运算,都为1则为1,否则为0
|:或运算,全为0则为0,否则为1
^:异或运算,相同为0,不同为1
代码:
int singleNumber(int* nums, int numsSize) {
int count = 0;
if(numsSize == 0) return 0;
if(numsSize == 1) return nums[0];
for(int i=0;i<numsSize;i++){
count = count ^ nums[i];
}
return count;
}