[容易]落单的数
题目来源:http://www.lintcode.com/zh-cn/problem/single-number/
方法:
异或满足交换律,任意两个相同的数可以异或是0。0和任何数异或的结果是该数,那么最后的结果一定是落单的数字。
C++版 VS2012测试通过:
1 //#include <iostream>
2 //#include <vector>
3 //#include <queue>
4 //#include <algorithm>
5 //using namespace std;
6
7 class Solution {
8 public:
9 /**
10 * @param A: Array of integers.
11 * return: The single number.
12 */
13 int singleNumber(vector<int> &A) {
14 // write your code here
15 int x=0;
16 for (int i = 0; i < A.size(); i++) {
17 x ^= A[i];
18 }
19 return x;
20 }
21 };
22
23 //测试
24 //int main()
25 //{
26 // Solution s;
27 // int a[]={1,2,2,1,3,4,3};
28 // int i=sizeof(a)/sizeof(int);
29 // vector<int> v(a,a+i);
30 // cout<<s.singleNumber(v);
31 //}
Python2.7版 spider测试通过:
1 class Solution:
2 """
3 @param A : an integer array
4 @return : a integer
5 """
6 def singleNumber(self, A):
7 # write your code here
8 ans = 0;
9 for x in A:
10 ans = ans ^ x
11 return ans
12 #测试
13 #if __name__=='__main__':
14 # s=Solution()
15 # n=[1,2,2,1,3,4,3]
16 # print s.singleNumber(n)
-------------------------------------------------
原创博客 转载请注明出处http://www.cnblogs.com/hslzju
-------------------------------------------------