LeetCode--Single Number II

Given an array of integers, every element appears three times except for one. Find that single one.

Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

class Solution 
{
public:
    int singleNumber(int A[], int n) 
    {
        if(n==0)
            return -1;
        const int num = 32;
        int bit[num];
        for(int i=0; i<num; i++)
            bit[i] = 0;
        for(int i=0;i<n;i++)
        {
            int temp = A[i];
            for(int j=num-1;j>=0;j--)
            {
                bit[j] = bit[j]+(temp&1);
                temp = temp>>1;
                bit[j] = bit[j]%3;
            }
        }
        int res = 0;
        for(int j=0; j<num; j++)
            res = res*2 + bit[j];
        return res;
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章