LeetCode OJ--Single Number II **

https://oj.leetcode.com/problems/single-number-ii/

有一列数,其中有1个数的个数不是3的倍数,求出这个数。

学习了别人的思路,按照二进制,统计每个位上1的个数,3个相同的数的话,它们的二进制表示是相同的,则同一个位置上,必然1的个数是3,所以 % 3,变成0,相当于消去了相同的数。

而在提交了代码之后,出现了 wrong answer. 咔咔研究了代码之后发现,对于负数的话,这个表示是不对的。 -11 % 2 == -1,  对于-1 存到位数统计之后,会影响对3的求余, -1就中和掉原来的1了。影响了个数。

#include <iostream>
#include <vector>;
using namespace std;

class Solution {
public:
    int singleNumber(int A[], int n) {
        //a int has 32 bits
        int word = sizeof(int) * 8;
        vector<int> wordDigit;
        wordDigit.resize(word);
        for(int i = 0;i<word;i++)
            wordDigit[i] = 0;

        int _numA;
        int negativeNum = 0; //统计负数的个数
        for(int i = 0;i<n;i++)
        {
            int weishu = 0;
            _numA = A[i];
            if(A[i]<0)
            {
                _numA = - A[i];
                negativeNum++;
            }
            while(_numA)
            {
                wordDigit[weishu] += _numA%2;
                wordDigit[weishu] = wordDigit[weishu]%3;
                _numA = _numA/2;
                weishu++;
            }
        }
        int ans = 0;
        for(int i = word -1;i >=0;i--)
            ans = ans*2 + wordDigit[i];
        //一个数出现了2次,其他都出现了3次
        if(n%3 ==2)
            ans = ans/2;
        //如果这个数是负数
        if(negativeNum%3!=0)
            ans *= -1;
        return ans;
    }
};

int main()
{
    int A[4] = {-3,-3,-3,3};
    class Solution sol;
    int ans = sol.singleNumber(A,4);
    cout<< -11 %2 <<" "<< -11/2 <<endl;
    cout<<ans<<endl;
}
原文地址:https://www.cnblogs.com/qingcheng/p/3788720.html