Skip to content

Commit 16fe71e

Browse files
committed
[LeetCode Sync] Runtime - 0 ms (100.00%), Memory - 17.7 MB (51.14%)
1 parent 28bb79a commit 16fe71e

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
<p>Given a positive integer <code>n</code>, write a function that returns the number of <span data-keyword="set-bit">set bits</span> in its binary representation (also known as the <a href="http://en.wikipedia.org/wiki/Hamming_weight" target="_blank">Hamming weight</a>).</p>
2+
3+
<p>&nbsp;</p>
4+
<p><strong class="example">Example 1:</strong></p>
5+
6+
<div class="example-block">
7+
<p><strong>Input:</strong> <span class="example-io">n = 11</span></p>
8+
9+
<p><strong>Output:</strong> <span class="example-io">3</span></p>
10+
11+
<p><strong>Explanation:</strong></p>
12+
13+
<p>The input binary string <strong>1011</strong> has a total of three set bits.</p>
14+
</div>
15+
16+
<p><strong class="example">Example 2:</strong></p>
17+
18+
<div class="example-block">
19+
<p><strong>Input:</strong> <span class="example-io">n = 128</span></p>
20+
21+
<p><strong>Output:</strong> <span class="example-io">1</span></p>
22+
23+
<p><strong>Explanation:</strong></p>
24+
25+
<p>The input binary string <strong>10000000</strong> has a total of one set bit.</p>
26+
</div>
27+
28+
<p><strong class="example">Example 3:</strong></p>
29+
30+
<div class="example-block">
31+
<p><strong>Input:</strong> <span class="example-io">n = 2147483645</span></p>
32+
33+
<p><strong>Output:</strong> <span class="example-io">30</span></p>
34+
35+
<p><strong>Explanation:</strong></p>
36+
37+
<p>The input binary string <strong>1111111111111111111111111111101</strong> has a total of thirty set bits.</p>
38+
</div>
39+
40+
<p>&nbsp;</p>
41+
<p><strong>Constraints:</strong></p>
42+
43+
<ul>
44+
<li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li>
45+
</ul>
46+
47+
<p>&nbsp;</p>
48+
<strong>Follow up:</strong> If this function is called many times, how would you optimize it?
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
class Solution:
2+
def hammingWeight(self, n: int) -> int:
3+
result = 0
4+
while n:
5+
n -= n & -n
6+
result += 1
7+
return result

0 commit comments

Comments
 (0)