Skip to content

Commit 2952f11

Browse files
committed
feat(cpp): add lonely_integer.cpp
1 parent a50c105 commit 2952f11

File tree

1 file changed

+13
-0
lines changed

1 file changed

+13
-0
lines changed
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
#include <vector>
2+
3+
int lonelyInteger(std::vector<int>& nums) {
4+
int res = 0;
5+
// XOR each element of the array so that duplicate values will
6+
// cancel each other out (x ^ x == 0).
7+
for (int i = 0; i < nums.size(); i++) {
8+
res ^= nums[i];
9+
}
10+
// 'res' will store the lonely integer because it would not have
11+
// been canceled out by any duplicate.
12+
return res;
13+
}

0 commit comments

Comments
 (0)