首页 > 代码库 > 137. Single Number II

137. Single Number II

 1 class Solution { 2 public: 3     int singleNumber(vector<int>& nums) { 4         int len = sizeof(nums[0]) * 8; 5         vector<int> count(len, 0); 6         for (size_t i = 0; i < nums.size(); ++i) { 7             int cmp = 1; 8             for (int j = 0; j < len; ++j) { 9                 //if (nums[i] < cmp) break; // 要特别注意这里,数值可能为负值,这样判小就会出现错误10                 if (nums[i] & cmp) {11                     ++count[j];12                     count[j] = count[j] % 3;13                 }14                 cmp <<= 1;15             }16         }17         int num = 0;18         for (int i = 0; i < len; ++i) {19             if (count[i]) num += (count[i] << i);// 如果调用pow函数,如果是负值就会出现错误,要考虑全面20         }21         return num;22     }23 };

 

137. Single Number II