MCPcopy Create free account
hub / github.com/codedecks-in/LeetCode-Solutions / singleNumber

Method singleNumber

C++/Single-Number-III.cpp:9–35  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

7class Solution {
8public:
9 vector<int> singleNumber(vector<int>& nums) {
10 int xor_all = 0;
11 // Get the XOR value of all the numbers in the vector
12 for(int num: nums) xor_all ^= num;
13 // xor_all will contain a^b, where a and b are repeated only once.
14 // if value of a bit in xor is 1, then it means either a or b has
15 // 1 in that position, but not both. We can use this to find the answer.
16 int setbit = 1;
17 // Find the first position in xor_all where the value is 1
18 while((setbit & xor_all) == 0)
19 setbit <<= 1;
20
21 vector<int> result(2);
22
23 // We basically split the numbers into two sets.
24 // All numbers in first set will have a bit in the setbit position.
25 // Second set of numbers, will have 0 in the setbit position.
26 for(int num: nums) {
27 if(num & setbit) {
28 result[0] ^= num;
29 } else {
30 result[1] ^= num;
31 }
32 }
33
34 return result;
35 }
36};

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected