forked from keon/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcount_ones.py
More file actions
56 lines (42 loc) · 1.21 KB
/
count_ones.py
File metadata and controls
56 lines (42 loc) · 1.21 KB
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
"""
Count Ones (Hamming Weight)
Count the number of 1-bits in the binary representation of an unsigned
integer using Brian Kernighan's algorithm.
Reference: https://en.wikipedia.org/wiki/Hamming_weight
Complexity:
Time: O(k) where k is the number of set bits
Space: O(1) iterative / O(k) recursive (call stack)
"""
from __future__ import annotations
def count_ones_recur(number: int) -> int:
"""Count set bits using Brian Kernighan's algorithm (recursive).
Args:
number: A non-negative integer.
Returns:
The number of 1-bits in the binary representation.
Examples:
>>> count_ones_recur(8)
1
>>> count_ones_recur(63)
6
"""
if not number:
return 0
return 1 + count_ones_recur(number & (number - 1))
def count_ones_iter(number: int) -> int:
"""Count set bits using Brian Kernighan's algorithm (iterative).
Args:
number: A non-negative integer.
Returns:
The number of 1-bits in the binary representation.
Examples:
>>> count_ones_iter(8)
1
>>> count_ones_iter(63)
6
"""
count = 0
while number:
number &= number - 1
count += 1
return count