public class TestDemo01 {
public static void main(String[] args) {
int[] singles = {1, 3, 4, 2, 6, 1, 3, 6, 2, 8, 4};
singleNumber(singles);
//(1^1)^(2^2)^(3^3)^(4^4)^(6^6)^8=0^0^0^0^0^8=8
}
public static int singleNumber(int[] nums) {
/**本题可使用异或的方法解决
1.任何数与零异或都为其本身
2.相同的两个数异或为0
3.异或运算满足交换律与结合律
*/
int single = 0;
//将数组中的所有元素进行异或运算,结果便为只出现一次的元素
for (int num : nums) {
single ^= num;
}
System.out.println(single);
return single;
}
}