[leetcode]762. Prime Number of Set Bits in Binary Representation

[leetcode]762. Prime Number of Set Bits in Binary Representation


Analysis

周一快乐~—— [ummm~]

Given two integers L and R, find the count of numbers in the range [L, R] (inclusive) having a prime number of set bits in their binary representation.
(Recall that the number of set bits an integer has is the number of 1s present when written in binary. For example, 21 written in binary is 10101 which has 3 set bits. Also, 1 is not a prime.)
把十进制数转换成二进制,然后求出其set bits(有多少位是1),再判断set bits是否是素数~
但是两种方法效率都很差,求大神指路,给个高效算法!!

Implement

方法一

class Solution {
public:
    int countPrimeSetBits(int L, int R) {
        int res = 0;
        for(int i=L; i<=R; i++){
            int cnt = 0;
            int t = i;
            while(t){
                if(t%2 == 1)
                    cnt++;
                t /= 2;
            }
            if(isPrim(cnt))
                res++;
        }
        return res;
    }
    bool isPrim(int num){
        if(num < 2)
            return false;
        for(int i=2; i<=(int)sqrt((double)num); i++){
            if(num%i == 0)
                return false;
        }
        return true;
    }
};

方法二(因为他给出了L和R的范围,所以可以事先求出区间内所有的素数,然后再进行判断)

class Solution {
public:
    int countPrimeSetBits(int L, int R) {
        int len = log((double)1000000)/log((double)2);
        bool prim[len+1] = {false};
        for(int i=0; i<=len; i++){
            if(isPrim(i))
                prim[i] = true;
        }
        int res = 0;
        for(int i=L; i<=R; i++){
            int cnt = 0;
            int t = i;
            while(t){
                if(t%2 == 1)
                    cnt++;
                t /= 2;
            }
            if(prim[cnt])
                res++;
        }
        return res;
    }
    bool isPrim(int num){
        if(num < 2)
            return false;
        for(int i=2; i<=(int)sqrt((double)num); i++){
            if(num%i == 0)
                return false;
        }
        return true;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_32135877/article/details/81282161