Prime Number of Set Bits in Binary Representation

题目

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.)

答案

class Solution {
    public int countPrimeSetBits(int L, int R) {
        int[] numSetBits = new int[1000000];
        int[] primes = {2,3,5,7,11,13,17,19,23,29,31};
        Set hash = new HashSet();
        for(int i = 0; i < primes.length; i++) hash.add(primes[i]);
        int ans = 0;    
        for(int i = L; i <= R; i++) {
            int num;
            int first = i >> 1;
            int second = i & 1;
            if(numSetBits[first] != 0 && numSetBits[second] != 0)
                numSetBits[i] = num = numSetBits[first] + numSetBits[second];
            else
                num = hammingWeight(i);                
            if(hash.contains(num)) ans++;
        }
        return ans;
    }
    
    public int hammingWeight(int n) {
        int ones = 0;
        while(n!=0) {
            ones = ones + (n & 1);
            n = n>>>1;
        }
        return ones;
    }

}

你可能感兴趣的:(Prime Number of Set Bits in Binary Representation)