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不同为1.
/
/
按位与运算&
System.out.println(
0
&
0
);
/
/
0
System.out.println(
0
&
1
);
/
/
0
System.out.println(
1
&
1
);
/
/
1
System.out.println(
"==========="
);
/
/
按位或运算符|
System.out.println(
0
|
0
);
/
/
0
System.out.println(
0
|
1
);
/
/
1
System.out.println(
1
|
1
);
/
/
1
System.out.println(
"==========="
);
/
/
异或运算符^
System.out.println(
0
^
0
);
/
/
0
System.out.println(
0
^
1
);
/
/
1
System.out.println(
1
^
1
);
/
/
0
System.out.println(
"==========="
);
public class Solution {
public int singleNumber(int[] nums) {
int result = 0;
int n =nums.length;
for (int i = 0; i<n; i++)
{
result ^=nums[i];
}
return result;
}
}