【Leetcode_easy】762. Prime Number of Set Bits in Binary Representation

博客围绕Leetcode的762题“二进制表示中质数个置位”展开。因题目给定数的范围R <= 106 < 220,统计非零位个数cnt后,只需检测其是否为20以内的质数,可将20以内质数放入HashSet,再进行查找。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

problem

762. Prime Number of Set Bits in Binary Representation

solution1:

class Solution {
public:
    int countPrimeSetBits(int L, int R) {
        int res = 0;
        int bits = 0;
        for(int i=L; i<=R; i++)
        {
            bits = countBits(i);
            if(isPrime(bits) && bits!=1 ) res++;//err...
        }
        return res;
    }
    int countBits(int num)
    {
        int res = 0;
        while(num>0)
        {
            if(num & 1 == 1) res++;
            num >>= 1;
        }
        return res;
    }
    bool isPrime(int num)
    {
        for(int i=sqrt(num); i>1; i--)
        {
            if(num%i==0) return false;
        }
        return true;

    }
};

solution2:题目中给了数的大小范围 R <= 106 < 220,那么统计出来的非零位个数cnt只需要检测是否是20以内的质数即可,所以将20以内的质数都放入一个HashSet中,然后统计出来cnt后,直接在HashSet中查找有没有即可。

class Solution {
public:
    int countPrimeSetBits(int L, int R) {
        int res = 0;
        unordered_set<int> primes{2, 3, 5, 7, 11, 13, 17, 19};
        for(int i=L; i<=R; i++)
        {
            int bits = 0;
            int tmp = i;
            while(tmp){
                if(tmp&1 == 1) bits++;
                tmp >>= 1;
            }
            res += primes.count(bits);
        }
        return res;
    }
};

参考

1. Leetcode_easy_762. Prime Number of Set Bits in Binary Representation;

2. Grandyang;

转载于:https://www.cnblogs.com/happyamyhope/p/11171617.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值