Skip to content

Commit 9f61a42

Browse files
NoyeArkcursoragent
andcommitted
feat: 20260221 check in
Co-authored-by: Cursor <cursoragent@cursor.com>
1 parent d98902a commit 9f61a42

1 file changed

Lines changed: 59 additions & 0 deletions

File tree

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
# [762. 二进制表示中质数个计算置位](https://leetcode.cn/problems/prime-number-of-set-bits-in-binary-representation/description/)
2+
3+
> **日期**:2026-02-21
4+
> **所用时间**:4min
5+
> **知识点**:位运算、质数判定
6+
7+
## 1. 题目描述
8+
9+
给你两个整数 `left``right`,在闭区间 `[left, right]` 内,统计满足「**二进制表示中 1 的个数是质数**」的整数个数。
10+
11+
**计算置位**即二进制中 `1` 的个数。例如 `21` 的二进制为 `10101`,有 3 个计算置位。
12+
13+
**示例 1:**
14+
15+
```
16+
输入:left = 6, right = 10
17+
输出:4
18+
解释:6→110(2 个 1,2 是质数)、7→111(3,质数)、8→1000(1,非质数)、9→1001(2,质数)、10→1010(2,质数),共 4 个。
19+
```
20+
21+
**示例 2:**
22+
23+
```
24+
输入:left = 10, right = 15
25+
输出:5
26+
解释:10(2)、11(3)、12(2)、13(3)、14(3)、15(4 非质数),共 5 个。
27+
```
28+
29+
**提示:**
30+
31+
- `1 <= left <= right <= 10^6`
32+
- `right - left <= 10^4`
33+
34+
## 2. 遍历 + 位运算 + 质数判定
35+
36+
`[left, right]` 中每个数 `x`,用 `x.bit_count()`(或 `bin(x).count('1')`)得到二进制中 1 的个数;再判断该个数是否为质数(如用试除法或打表,因位数最多约 20,质数只有 2,3,5,7,11,13,17,19)。满足则计数 +1。
37+
38+
复杂度分析:
39+
- **时间复杂度**:$O((\textit{right}-\textit{left}+1) \cdot \sqrt{20})$,质数判定上界很小。
40+
- **空间复杂度**:$O(1)$(或 $O(1)$ 打表)。
41+
42+
**Python3**
43+
44+
```python
45+
class Solution:
46+
def countPrimeSetBits(self, left: int, right: int) -> int:
47+
@cache
48+
def is_prime(x):
49+
if x < 2:
50+
return False
51+
i = 2
52+
while i * i <= x:
53+
if x % i == 0:
54+
return False
55+
i += 1
56+
return True
57+
58+
return sum(int(is_prime(x.bit_count())) for x in range(left, right + 1))
59+
```

0 commit comments

Comments
 (0)