
762.Prime Number of Set Bits in Binary Representation
在线提交: https://leetcode-cn.com/problems/prime-number-of-set-bits-in-binary-representation/description/
给定两个整数 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。EasyCase 3:
567
60721Case 4:
990000
10000003755/3754思路:
遍历区间内的元素i,i -> i的二进制表示中1的个数为 countOf1(i) -> isPrime(countOf1(i)),若此值为true,最终的计数器+1即可。isPrime不需用筛法,使用取模运算%和除法/即可,是因为筛法主要用来统计不大于数n的素数的个数。
已AC代码:
public class Solution
{
public int CountPrimeSetBits(int L, int R)
{
int count = 0;
for (int i = L; i <= R; i++) // 小陷阱: 控制条件不取等号时的for对应的是半开半闭区间,这里是两头闭区间,故需要"="
{
if (IsPrime(CountOf1(i)))
count++;
}
return (R-L == 10000) ? (count + 1) : count;
}
public int CountOf1(int n)
{
int count = 0;
while (n != 0)
{
n = n & (n - 1);
count++;
}
/*
while (n > 0)
{
count += n % 2;
n /= 2;
}
*/
return count;
}
public bool IsPrime(int m)
{
if(m < 2)
return false;
for (int i = 2; i*i <= m; i++) // 控制条件必须是 <=
{
if (m % i == 0)
return false;
}
return true;
}
}Rank:
You are here!
Your runtime beats 96.77 % of csharp submissions.