Skip to content

Commit e78c998

Browse files
committed
[LeetCode Sync] Runtime - 21 ms (97.65%), Memory - 19.4 MB (64.02%)
1 parent d0e8267 commit e78c998

2 files changed

Lines changed: 66 additions & 0 deletions

File tree

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
<p>Given two integers <code>left</code> and <code>right</code>, return <em>the <strong>count</strong> of numbers in the <strong>inclusive</strong> range </em><code>[left, right]</code><em> having a <strong>prime number of set bits</strong> in their binary representation</em>.</p>
2+
3+
<p>Recall that the <strong>number of set bits</strong> an integer has is the number of <code>1</code>&#39;s present when written in binary.</p>
4+
5+
<ul>
6+
<li>For example, <code>21</code> written in binary is <code>10101</code>, which has <code>3</code> set bits.</li>
7+
</ul>
8+
9+
<p>&nbsp;</p>
10+
<p><strong class="example">Example 1:</strong></p>
11+
12+
<pre>
13+
<strong>Input:</strong> left = 6, right = 10
14+
<strong>Output:</strong> 4
15+
<strong>Explanation:</strong>
16+
6 -&gt; 110 (2 set bits, 2 is prime)
17+
7 -&gt; 111 (3 set bits, 3 is prime)
18+
8 -&gt; 1000 (1 set bit, 1 is not prime)
19+
9 -&gt; 1001 (2 set bits, 2 is prime)
20+
10 -&gt; 1010 (2 set bits, 2 is prime)
21+
4 numbers have a prime number of set bits.
22+
</pre>
23+
24+
<p><strong class="example">Example 2:</strong></p>
25+
26+
<pre>
27+
<strong>Input:</strong> left = 10, right = 15
28+
<strong>Output:</strong> 5
29+
<strong>Explanation:</strong>
30+
10 -&gt; 1010 (2 set bits, 2 is prime)
31+
11 -&gt; 1011 (3 set bits, 3 is prime)
32+
12 -&gt; 1100 (2 set bits, 2 is prime)
33+
13 -&gt; 1101 (3 set bits, 3 is prime)
34+
14 -&gt; 1110 (3 set bits, 3 is prime)
35+
15 -&gt; 1111 (4 set bits, 4 is not prime)
36+
5 numbers have a prime number of set bits.
37+
</pre>
38+
39+
<p>&nbsp;</p>
40+
<p><strong>Constraints:</strong></p>
41+
42+
<ul>
43+
<li><code>1 &lt;= left &lt;= right &lt;= 10<sup>6</sup></code></li>
44+
<li><code>0 &lt;= right - left &lt;= 10<sup>4</sup></code></li>
45+
</ul>
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
class Solution:
2+
def countPrimeSetBits(self, left: int, right: int) -> int:
3+
N = 22
4+
sieve = [True] * N
5+
sieve[0] = sieve[1] = False
6+
7+
i = 2
8+
while i*i < N:
9+
if sieve[i] < N:
10+
for j in range(i*i, N, i):
11+
sieve[j] = False
12+
i += 1
13+
14+
res = 0
15+
16+
for i in range(left, right+1):
17+
#if sieve[bin(i)[2:].count('1')]:
18+
if sieve[i.bit_count()]:
19+
res += 1
20+
21+
return res

0 commit comments

Comments
 (0)