File tree Expand file tree Collapse file tree 2 files changed +55
-0
lines changed
Solutions/0191-number-of-1-bits Expand file tree Collapse file tree 2 files changed +55
-0
lines changed Original file line number Diff line number Diff line change 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 >  ; </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 >  ; </p >
41+ <p ><strong >Constraints:</strong ></p >
42+
43+ <ul >
44+ <li><code>1 <= n <= 2<sup>31</sup> - 1</code></li>
45+ </ul >
46+
47+ <p >  ; </p >
48+ <strong >Follow up:</strong > If this function is called many times, how would you optimize it?
Original file line number Diff line number Diff line change 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
You can’t perform that action at this time.
0 commit comments