Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Count set bits in a range?
A given positive number when converted to binary has a number of set bits. Set bits in a binary number are represented by 1. In this article we will see how to count the number of set bits in a specific range of positions within a binary representation of a number.
Using bin() and String Slicing
In the below example we take a number and apply the bin() function to get the binary value. Then we slice it to remove the prefixes and count set bits in the specified range ?
Example
def SetBits_cnt(n, l, r):
bin_val = bin(n)
# Remove '0b' prefixed in bin_val conversion
bin_val = bin_val[2:]
print("Binary representation:", bin_val)
# reverse string to count from right (LSB)
bin_val = bin_val[-1::-1]
# count all set bit '1' starting from index l-1 to r-1
count = len([bin_val[i] for i in range(l - 1, r) if i < len(bin_val) and bin_val[i] == '1'])
print("Set bits in range [{}, {}]:".format(l, r), count)
return count
SetBits_cnt(83, 1, 6)
Output
Running the above code gives us the following result ?
Binary representation: 1010011 Set bits in range [1, 6]: 3
Using Bitwise Operations
The bitwise operator approach is more efficient. We create a mask to extract bits in the specified range, then count the set bits using Brian Kernighan's algorithm ?
Example
def trackBitsInRange(n, l, r):
# Create mask using bitwise operator
mask = ((1 << r) - 1) ^ ((1 << (l - 1)) - 1)
# Extract bits in range and count set bits
return trackSetBits(n & mask)
def trackSetBits(n):
count = 0
while n:
n &= (n - 1) # Brian Kernighan's algorithm
count += 1
return count
# Example usage
number = 83
left = 1
right = 6
print("Number:", number)
print("Binary:", bin(number))
print("Set bits in range [{}, {}]:".format(left, right), trackBitsInRange(number, left, right))
Output
Running the above code gives us the following result ?
Number: 83 Binary: 0b1010011 Set bits in range [1, 6]: 3
Comparison
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| String Slicing | O(log n) | O(log n) | Simple understanding |
| Bitwise Operations | O(set bits) | O(1) | Performance |
How Range Works
In both methods, the range [l, r] represents bit positions from right to left (1-indexed). For number 83 (binary: 1010011):
- Position 1: 1 (rightmost bit)
- Position 2: 1
- Position 3: 0
- Position 4: 0
- Position 5: 1
- Position 6: 0
Range [1, 6] includes positions 1, 2, 3, 4, 5, giving us 3 set bits.
Conclusion
Use the bitwise approach for better performance with O(1) space complexity. The string slicing method is easier to understand but requires more memory for string operations.
