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?
Solution in Java:
public class Solution {
public int singleNumber(int[] A) {
int num=0;
for(int i=0; i<A.length; i++){
num = num^A[i];
}
return num;
}
}
Note: ^是按位异或符号,遵守交换律和结合律,0与任何数异或结果均为该数。注意复习逻辑运算符。
参考资料:http://help.topcoder.com/data-science/competing-in-algorithm-challenges/algorithm-tutorials/a-bit-of-fun-fun-with-bits/