Given an array of integers, every element appears twice except for one. Find that single one.
非常简单的一道题。
直接相异或剩下的那个数就是答案。原理是两个相等的数异或的值为0。
1 class Solution { 2 public: 3 int singleNumber(int A[], int n) { 4 int temp; 5 for(int i=0;i!=n;i++) 6 temp=temp^A[i]; 7 return temp; 8 } 9 };
Given an array of integers, every element appears three times except for one. Find that single one.
用好位运算,多看看与或非到底能做什么。
1 class Solution { 2 public: 3 int singleNumber(int A[], int n) { 4 int one=0,two=0,three=0; 5 for(int i=0;i!=n;i++){ 6 three = A[i] & two; 7 two=two | (one & A[i]); 8 one = one | A[i]; 9 one = one & ~three; 10 two = two & ~three; 11 } 12 return one; 13 } 14 };