例题
找出一组int【】中的只出现一次的数字。
1,1,2,2,3
输出3
5,5,6,6,8,7,8
输出7
代码
public class Solution {
public static void main(String[] args) {
int [] aa= new int[] {4,1,2,1,2};
//交换律验证 和int的异或操作原理begin
System.out.println(3^1^2^4);
//011 3
//001 1
//010 2
//100 4
System.out.println(1^2^4^3);
//001 1
//010 2
//100 4
//011 3
//交换律验证 和int的异或操作原理end
//aa为41212交换顺序为11224运算顺序为1^1->0,2^2->0,0^0->0,0^4->4
System.out.println(singleNumber(aa));
//结果为四
}
public static int singleNumber(int[] nums) {
int single = 0;
for (int num : nums) {
single ^= num;
}
return single;
}
}
异或规则
相同为0不同为1
3^1^2^4
//011 3
//001 1
//010 2
//100 4
结果为100
1^2^4^3
//001 1
//010 2
//100 4
//011 3
结果为100
符合交换律