[LeetCode] Single Number III

Try to split all the numbers into two groups with each of the target one in different groups. Refer to this link for a nice explanation.

The code is written as follows.

 1 class Solution {
 2 public:
 3     vector<int> singleNumber(vector<int>& nums) {
 4         int t = 0, p, first = 0, second = 0;
 5         for (int num : nums) t ^= num;
 6         for (p = 0; p < 32; p++)
 7             if ((t >> p) & 1) break;
 8         for (int num : nums) {
 9             if ((num >> p) & 1) first ^= num;
10             else second ^= num;
11         }
12         return {first, second};
13     }
14 };

 

posted @ 2015-08-17 16:16  jianchao-li  阅读(191)  评论(0编辑  收藏  举报