-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path191_number_of_1_bits.py
More file actions
41 lines (33 loc) · 902 Bytes
/
191_number_of_1_bits.py
File metadata and controls
41 lines (33 loc) · 902 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
class Solution:
def hammingWeight(self, n: int) -> int:
ans = 0
for s in bin(n)[2:]:
ans += s == '1'
return ans
def hammingWeight1(self, n: int) -> int:
return bin(n).count('1')
def hammingWeight2(self, n: int) -> int:
ans = 0
while n:
n, m = divmod(n, 2)
ans += m == 1
return ans
def hammingWeight3(self, n: int) -> int:
ans = 0
while n:
ans += n & 1
n >>= 1
return ans
def hammingWeight4(self, n: int) -> int:
ans = 0
while n:
ans += 1
n &= n-1
return ans
def test():
s = Solution()
for (n, target) in ((0, 0), (1, 1), (10, 2), (2**32-1, 32)):
ans = s.hammingWeight3(n)
assert ans == target, f"target {target}, got {ans}"
if __name__ == "__main__":
test()