LeetCode: Single Number II

这题有点难,网上大神的这段代码太牛了。

 1 class Solution {
 2 public:
 3     int singleNumber(int A[], int n) {
 4         // Note: The Solution object is instantiated only once and is reused by each test case.
 5         int one = 0;
 6         int two = 0;
 7         int three = 0;
 8         for(int i = 0 ; i < n ; i++){
 9             two |= A[i] & one;
10             one = A[i] ^ one;
11             three = ~(one&two);
12             one &= three;
13             two &= three;
14         }
15         return one;
16     }
17 };

这段代码就很好理解

 1 class Solution {
 2 public:
 3     int singleNumber(int A[], int n) {
 4         int ans = 0;
 5         for (int i = 0; i < 32; ++i) {
 6             int count = 0;
 7             for (int j = 0; j < n; ++j) count += (A[j] >> i) & 1;
 8             ans |= ((count % 3 != 0) << i);
 9         }
10         return ans;
11     }
12 };

 C#

 1 public class Solution {
 2     public int SingleNumber(int[] nums) {
 3         int ans = 0;
 4         for (int i = 0; i < 32; i++) {
 5             int count = 0;
 6             for (int j = 0; j < nums.Length; j++) count += (nums[j] >> i) & 1;
 7             ans |= ((count % 3 != 0? 1 : 0) << i);
 8         }
 9         return ans;
10     }
11 }
View Code
原文地址:https://www.cnblogs.com/yingzhongwen/p/3517359.html