Skip to content

Commit a837434

Browse files
Update single_number_ii.cpp
1 parent 95c3394 commit a837434

File tree

1 file changed

+41
-7
lines changed

1 file changed

+41
-7
lines changed

single_number_ii.cpp

Lines changed: 41 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,47 @@
11
class Solution {
22
public:
33
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
108
}
119
return ones;
1210
}
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+
*/

0 commit comments

Comments
 (0)