-
工具链接:位运算表
>问题: 一个数组中,一种数出现奇数次,其他数都是偶数次,怎么找出出现奇数次数的数? 如该数组为: int[] nums = {11, 22, 11, 33, 33, 22, 33}; >思路: 1. a^a=0 2. 0^a=a 3. a^a^b= 0^b >目的: 将数组中的全部数进行^运算,即可得到该落单数
-
方法代码:
public static int singleNumber(int[] nums) {
int num=nums[0];//将数组的第一个数拿出来
for (int i = 0; i <nums.length-1 ; i++) {
num^=nums[i+1];//将数组中的全部数进行^运算
}
return num;
}