【一次过】Lintcode 1046. 二进制表示中质数个计算置位

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/majichen95/article/details/82781873

给定两个整数 L 和 R ,找到闭区间[L, R] 范围内,计算置位位数为质数的整数个数。

(注意,计算置位代表二进制表示中1的个数。例如 21 的二进制表示 10101 有 3 个计算置位。还有,1 不是质数。)

样例

示例1:

输入: L = 6, R = 10
输出: 4
解释:
6 -> 110 (2 个计算置位,2 是质数)
7 -> 111 (3 个计算置位,3 是质数)
9 -> 1001 (2 个计算置位,2 是质数)
10-> 1010 (2 个计算置位,2 是质数)

示例 2:

输入: L = 10, R = 15
输出: 5
解释:
10 -> 1010 (2 个计算置位, 2 是质数)
11 -> 1011 (3 个计算置位, 3 是质数)
12 -> 1100 (2 个计算置位, 2 是质数)
13 -> 1101 (3 个计算置位, 3 是质数)
14 -> 1110 (3 个计算置位, 3 是质数)
15 -> 1111 (4 个计算置位, 4 不是质数)

注意事项

1.LR 是 L <= R 且在[1, 10^6] 中的整数。
2.R - L 的最大值为 10000


解题思路:

非常简单,直接上代码:

public class Solution {
    /**
     * @param L: an integer
     * @param R: an integer
     * @return: the count of numbers in the range [L, R] having a prime number of set bits in their binary representation
     */
    public int countPrimeSetBits(int L, int R) {
        // Write your code here
        int res = 0;
        
        for(int i=L ; i<=R ; i++){
            int bitCount = Integer.bitCount(i);
            if(isPrime(bitCount))
                res++;
        }
        
        return res;
    }
    
    public boolean isPrime(int num){
        if(num < 2)
            return false;
            
        for(int i=2 ; i<=Math.sqrt(num) ; i++){
            if(num%i == 0)
                return false;
        }
        
        return true;
    }
}

猜你喜欢

转载自blog.csdn.net/majichen95/article/details/82781873