题目描述:
给定两个整数 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 不是质数)
注意:
L, R 是 L <= R 且在 [1, 10^6] 中的整数。
R - L 的最大值为 10000。
方法1:
主要思路:
(1)获得每一个数字的二进制表示中 1 的个数,然后判断是否为质数;
(2)这里最大质数判读为19,是因为题目中数范围给出为,L, R 是 L <= R 且在 [1, 10^6] 中的整数;
class Solution {
public:
//统计当前数字的二进制表示中1的个数
int helper(int n){
int count=0;
while(n){
if(n&1)
++count;
n>>=1;
}
return count;
}
int countPrimeSetBits(int L, int R) {
int count=0;
while(L<=R){//对给出范围中的每个数进行统计判断
int x=helper(L);//获得当前数字的二进制表示中 1 的个数
//判断改个数是否为质数
if(x == 2 || x == 3 || x == 5 || x == 7 ||
x == 11 || x == 13 || x == 17 || x == 19)
++count;
++L;//获得下一个要判断的数字
}
return count;
}
};
以下代码只是使用哈希函数将需要判断的质数做了映射,并没有更快
class Solution {
public:
int helper(int n){
int count=0;
while(n){
if(n&1)
++count;
n>>=1;
}
return count;
}
int countPrimeSetBits(int L, int R) {
unordered_set<int> st;
st.insert(2);
st.insert(3);
st.insert(5);
st.insert(7);
st.insert(11);
st.insert(13);
st.insert(17);
st.insert(19);
int count=0;
while(L<=R){
if(st.count(helper(L)))
++count;
++L;
}
return count;
}
};