Skip to content

Commit a74fdff

Browse files
committed
Create number-of-1-bits.py
1 parent c0051b6 commit a74fdff

1 file changed

Lines changed: 24 additions & 0 deletions

File tree

Python/number-of-1-bits.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# Time: O(m)
2+
# Space: O(1)
3+
#
4+
# Write a function that takes an unsigned integer
5+
# and returns the number of ’1' bits it has (also known as the Hamming weight).
6+
#
7+
# For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011,
8+
# so the function should return 3.
9+
#
10+
# Credits:
11+
# Special thanks to @ts for adding this problem and creating all test cases.
12+
#
13+
class Solution:
14+
# @param n, an integer
15+
# @return an integer
16+
def hammingWeight(self, n):
17+
result = 0
18+
while n:
19+
n &= n - 1
20+
result += 1
21+
return result
22+
23+
if __name__ == '__main__':
24+
print Solution().hammingWeight(11)

0 commit comments

Comments
 (0)