Skip to content

Commit d40f742

Browse files
Sync LeetCode submission Runtime - 0 ms (100.00%), Memory - 8 MB (35.07%)
1 parent e02c516 commit d40f742

2 files changed

Lines changed: 61 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: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
class Solution {
2+
bool isPrimeBits(int n) {
3+
int bits = __builtin_popcount(n);
4+
if (bits == 1) return false;
5+
for (int i=2; i*i<=bits; i++) {
6+
if (bits % i == 0) return false;
7+
}
8+
return true;
9+
}
10+
public:
11+
int countPrimeSetBits(int left, int right) {
12+
int ans = 0;
13+
for (int i=left; i<=right; i++) ans += isPrimeBits(i);
14+
return ans;
15+
}
16+
};

0 commit comments

Comments
 (0)