【位运算】Single Number I&II

single number I

这道题没毛病,利用异或^的特性,直接AC:

class Solution {
public:
    int singleNumber(int A[], int n) {
        int ans=0;
        for(int i=0;i<n;i++)
            ans = ans ^ A[i];
        return ans;
    }
};

Single Number II

大致思路:

之前是想要清除出现两次的位。这里是想要清除出现三次的位

记录每个bit出现的次数,一个数搞不定就加两个数,用ones来记录只出现过一次的bits,用twos来记录只出现过两次的bits,ones&twos实际上就记录了出现过三次的bits,这时候我们来模拟进行出现3次就抵消为0的操作

每次先更新twos,然后再更新ones,ones和twos要同时清除出现三次的数,最后ones中保留的就是那个仅出现一次的数(的位)。

AC代码:

class Solution {
public:
    int singleNumber(int A[], int n) {
        int ones = 0;
        int twos = 0;
        int threes = 0;
        for(int i=0;i<n;i++)
        {
            int t = A[i];
            twos |= ones&t; //twos的更新要在ones抵消出现两次的数之前。
            ones ^= t;
            threes = twos&ones; //出现三次的数
            twos &= ~threes; //用取反~ 清除出现三次的数
            ones &= ~threes;
            
        }
        return ones;
    }
};

猜你喜欢

转载自blog.csdn.net/m0_38033475/article/details/91999486