To prove safety offer - Find 04 two-dimensional array

topic:

A unique array of numbers only appear.
In addition to an array of a number appears only once, other figures have appeared three times.
Find the number that appears only once.

 

answer:

If a number appears three times, then there three times its binary representation of each bit (0 or 1). Each bit of each binary digits add up if all three appear representation, then each and can be divisible by 3.
Each one adds up all the numbers we have an array of binary representation. If a bit and divisible by 3, then the number that appears only once in the corresponding binary representation of the one who is 0; otherwise, it is 1.

 

 1 class Solution
 2 {
 3 public:
 4     int findTheOnlyNum(vector<int>data)
 5     {
 6         if (data.size() == 0)return 0;
 7         for (auto a : data)    calTheBits(a);
 8         int res = 0;
 9         for (int i = 0; i < 32; ++i)
10             if (bits[i] % 3 == 1)res += pow(2, i);
11         return res;
12     }
13 private:
14     int bits[32] = { 0 };
15     void calTheBits(int num)
16     {
17         int n = 1;
18         for (int i = 0; i < 32; ++i)
19         {
20             if (num & n)bits[i]++;
21             n = n << 1;
22         }
23     }
24 };

 

Guess you like

Origin www.cnblogs.com/zzw1024/p/11707762.html