Skip to content

Commit 7abb692

Browse files
Merge pull request matthewsamuel95#144 from shivansh/single_number_variant
[Bit manipulation] Single element in array where every other element appears thrice
2 parents f81230e + bfabc77 commit 7abb692

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
// Given an array of integers, every element appears thrice except one. Find that single one.
2+
3+
#include <iostream>
4+
#include <vector>
5+
using namespace std;
6+
7+
int singleNumber(vector<int>& nums) {
8+
int ones = 0, twos = 0;
9+
10+
for (int i = 0; i < nums.size(); i++) {
11+
ones = (ones ^ nums[i]) & ~twos;
12+
twos = (twos ^ nums[i]) & ~ones;
13+
}
14+
15+
return ones;
16+
}
17+
18+
int main() {
19+
vector<int> nums = {3, 4, 2, 3, 3, 4, 4};
20+
cout << singleNumber(nums) << endl;
21+
return 0;
22+
}

0 commit comments

Comments
 (0)