Skip to content

Commit 007b673

Browse files
committed
[LeetCode Sync] Runtime - 3 ms (94.01%), Memory - 18.5 MB (59.13%)
1 parent e7ad463 commit 007b673

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
<p>Given an integer <code>n</code>, return <em>an array </em><code>ans</code><em> of length </em><code>n + 1</code><em> such that for each </em><code>i</code><em> </em>(<code>0 &lt;= i &lt;= n</code>)<em>, </em><code>ans[i]</code><em> is the <strong>number of </strong></em><code>1</code><em><strong>&#39;s</strong> in the binary representation of </em><code>i</code>.</p>
2+
3+
<p>&nbsp;</p>
4+
<p><strong class="example">Example 1:</strong></p>
5+
6+
<pre>
7+
<strong>Input:</strong> n = 2
8+
<strong>Output:</strong> [0,1,1]
9+
<strong>Explanation:</strong>
10+
0 --&gt; 0
11+
1 --&gt; 1
12+
2 --&gt; 10
13+
</pre>
14+
15+
<p><strong class="example">Example 2:</strong></p>
16+
17+
<pre>
18+
<strong>Input:</strong> n = 5
19+
<strong>Output:</strong> [0,1,1,2,1,2]
20+
<strong>Explanation:</strong>
21+
0 --&gt; 0
22+
1 --&gt; 1
23+
2 --&gt; 10
24+
3 --&gt; 11
25+
4 --&gt; 100
26+
5 --&gt; 101
27+
</pre>
28+
29+
<p>&nbsp;</p>
30+
<p><strong>Constraints:</strong></p>
31+
32+
<ul>
33+
<li><code>0 &lt;= n &lt;= 10<sup>5</sup></code></li>
34+
</ul>
35+
36+
<p>&nbsp;</p>
37+
<p><strong>Follow up:</strong></p>
38+
39+
<ul>
40+
<li>It is very easy to come up with a solution with a runtime of <code>O(n log n)</code>. Can you do it in linear time <code>O(n)</code> and possibly in a single pass?</li>
41+
<li>Can you do it without using any built-in function (i.e., like <code>__builtin_popcount</code> in C++)?</li>
42+
</ul>
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
class Solution:
2+
def countBits(self, n: int) -> List[int]:
3+
return [i.bit_count() for i in range(n + 1)]

0 commit comments

Comments
 (0)