问题
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?
描述
这个问题主要考察对于算术运算符的应用,注意任何数与0进行异或为其本身,两个相同的数进行异或为0,因此将数组中的所有的数进行异或剩余的为出现一次的
代码
public static int singleNumber(int[] nums) {
int a = 0;
for (int num : nums) {
a = a ^ num;
}
return a;
}