LeetCode 762 题解

https://leetcode.com/problems/prime-number-of-set-bits-in-binary-representation/description/

题目大意:问L到R之间的数二进制表示的时候,1的个数是质数的个数。

解题思路:暴力

class Solution {
    public int countPrimeSetBits(int L, int R) {
        Set<Integer> set  = new HashSet<>(Arrays.asList(2,3,5,7,11,13,17,19));
        int res=0;
        for(int i=L;i<=R;i++)
        {
            int tmp = i;
            int cnt =0;
            while(tmp!=0)
            {
                if( (tmp&1) ==1) cnt++;
                tmp>>=1;
            }
            if(set.contains(cnt)) res++;
        }
        return res;
    }
}

猜你喜欢

转载自blog.csdn.net/u011439455/article/details/80674722