|
4 | 4 | def get_set_bits_count_using_brian_kernighans_algorithm(number: int) -> int: |
5 | 5 | """ |
6 | 6 | Count the number of set bits in a 32 bit integer |
| 7 | + Uses Brian Kernighan's algorithm: the operation (number & (number - 1)) removes |
| 8 | + the rightmost set bit from the number. By repeating this until the number becomes |
| 9 | + zero, we count exactly how many set bits existed. |
| 10 | + Algorithm (Brian Kernighan's Method): |
| 11 | + 1. While number > 0: |
| 12 | + a. Execute: number &= (number - 1) # Removes the lowest set bit |
| 13 | + b. Increment counter |
| 14 | + 2. Return counter |
| 15 | + Why it works: (number - 1) flips all bits after the rightmost set bit. |
| 16 | + So (number & (number - 1)) removes only that one rightmost set bit. |
| 17 | + Example: 25 = 0b11001 |
| 18 | + - Iteration 1: 25 & 24 = 0b11001 & 0b11000 = 0b11000 (24) |
| 19 | + - Iteration 2: 24 & 23 = 0b11000 & 0b10111 = 0b10000 (16) |
| 20 | + - Iteration 3: 16 & 15 = 0b10000 & 0b01111 = 0b00000 (0) |
| 21 | + - Count: 3 set bits |
7 | 22 | >>> get_set_bits_count_using_brian_kernighans_algorithm(25) |
8 | 23 | 3 |
9 | 24 | >>> get_set_bits_count_using_brian_kernighans_algorithm(37) |
@@ -33,6 +48,24 @@ def get_set_bits_count_using_brian_kernighans_algorithm(number: int) -> int: |
33 | 48 | def get_set_bits_count_using_modulo_operator(number: int) -> int: |
34 | 49 | """ |
35 | 50 | Count the number of set bits in a 32 bit integer |
| 51 | +
|
| 52 | + Uses the basic approach: repeatedly check if the least significant bit (LSB) is set |
| 53 | + using the modulo operator, then right-shift to check the next bit. |
| 54 | +
|
| 55 | + Algorithm: |
| 56 | + 1. While number > 0: |
| 57 | + a. If number % 2 == 1, increment counter (LSB is 1) |
| 58 | + b. Right-shift number by 1 (number >>= 1) to check next bit |
| 59 | + 2. Return counter |
| 60 | +
|
| 61 | + Example: 25 = 0b11001 |
| 62 | + - Iteration 1: 25 % 2 = 1, count = 1, then 25 >> 1 = 12 |
| 63 | + - Iteration 2: 12 % 2 = 0, count = 1, then 12 >> 1 = 6 |
| 64 | + - Iteration 3: 6 % 2 = 0, count = 1, then 6 >> 1 = 3 |
| 65 | + - Iteration 4: 3 % 2 = 1, count = 2, then 3 >> 1 = 1 |
| 66 | + - Iteration 5: 1 % 2 = 1, count = 3, then 1 >> 1 = 0 |
| 67 | + - Count: 3 set bits |
| 68 | +
|
36 | 69 | >>> get_set_bits_count_using_modulo_operator(25) |
37 | 70 | 3 |
38 | 71 | >>> get_set_bits_count_using_modulo_operator(37) |
|
0 commit comments