File tree 1 file changed +41
-7
lines changed
1 file changed +41
-7
lines changed Original file line number Diff line number Diff line change 1
1
class Solution {
2
2
public:
3
3
int singleNumber (vector<int >& nums) {
4
- int ones = 0 ;
5
- int twos = 0 ;
6
-
7
- for ( const auto num : nums ){
8
- ones = ones^num & ~twos; // add num to the set of ones if num is not in the set of twos
9
- twos = twos^num & ~ones; // add num to the set of twos if num is not in the set of ones
4
+ int ones = 0 , twos = 0 ;
5
+ for (auto num : nums) {
6
+ ones = ones ^ num & ~twos; // if num not in twos, add it to ones
7
+ twos = twos ^ num & ~ones; // if num not in ones, add it to twos
10
8
}
11
9
return ones;
12
10
}
13
- };
11
+ };
12
+
13
+
14
+ /*
15
+ Previous attempt -
16
+
17
+ class Solution {
18
+ public:
19
+ int singleNumber(vector<int>& nums) {
20
+
21
+ int n=nums.size();
22
+ long ans;
23
+ int x, t;
24
+ ans=0;
25
+ int p=0;
26
+ // We have 32 bits integers as input
27
+ for(int i=0;i<32;i++)
28
+ {
29
+ t=0;
30
+ //calculate sum of ith bit for all numbers in nums
31
+ for(int j=0;j<n;j++)
32
+ {
33
+ x=nums[j]&1;
34
+ t=t+x;
35
+ nums[j]=nums[j]>>1;
36
+ }
37
+ t=t%3;
38
+ //the bit that does not occur as multiple of 3 is left as a remainder
39
+ ans=ans+t*pow(2,p);
40
+ p++;
41
+ }
42
+ return ans;
43
+ }
44
+ };
45
+
46
+
47
+ */
You can’t perform that action at this time.
0 commit comments