Appearance
0762-二进制表示中质数个计算置位
https://leetcode.cn/problems/prime-number-of-set-bits-in-binary-representation
给你两个整数 left 和 right ,在闭区间 [left, right] 范围内,统计并返回 计算置位位数为质数 的整数个数。 计算置位位数 就是二进制表示中 1 的个数。 例如, 21 的二进制表示 10101 有 3 个计算置位。
示例 1:
输入:left = 6, right = 10
输出:4
解释:
6 -> 110 (2 个计算置位,2 是质数)
7 -> 111 (3 个计算置位,3 是质数)
9 -> 1001 (2 个计算置位,2 是质数)
10-> 1010 (2 个计算置位,2 是质数)
共计 4 个计算置位为质数的数字。
示例 2:
输入:left = 10, right = 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 不是质数)
共计 5 个计算置位为质数的数字。
提示:
- 1 <= left <= right <= 10^6
- 0 <= right - left <= 10^4
思路
分两步,
- 计算置为,即bit=1的个数
- 计算总个数是否为质数,根据数据范围定义32位数之内是否为质数
参考代码
csharp
public class Solution {
// 数组返回时 1-10^6 最多7位,使用hash表表示是否是质数
private int calcBits(int num){
int count = 0;
while(num > 0){
count += num & 1;
num = num >> 1;
}
return count;
}
public int CountPrimeSetBits(int left, int right) {
Dictionary<int,int> dict = new Dictionary<int,int>();
//找出32为之内的质数
dict.Add(2,1);
dict.Add(3,1);
dict.Add(5,1);
dict.Add(7,1);
dict.Add(11,1);
dict.Add(13,1);
dict.Add(17,1);
dict.Add(19,1);
dict.Add(23,1);
dict.Add(29,1);
dict.Add(31,1);
int total = 0;
for(int i=left; i<=right; i++){
int bits = calcBits(i);
if(dict.ContainsKey(bits)){
total += dict[bits];
}
}
return total;
}
}
AlgoPress