Given a large binary number.The task is to count the number of 1’s in a given range from L to R (1 based indexing).
Input : s = “101101011010100000111”, L = 6, R = 15
Output : 5
s [L : R] = “1011010100”
There is only 5 set bits.
Input : s = “10110”, L = 2, R = 5
Output : 2
- Convert the string of size len to the bitset of size N.
- There is no need of (N – len) + (L – 1) bits in the left side and (N – R) bits in the right side of the bitset .
- Remove those bits efficiently using left and right shift bitwise operation.
- Now there are all zeroes in the left side of L and right side of R, so just use count() function to get the count of 1’s in the bitset as all positions except [L, R] are ‘0’.
Below is the implementation of above approach:
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Count set bits in a range
- Range query for count of set bits
- Python | Count set bits in a range
- Count unset bits in a range
- Check if bits of a number has count of consecutive set bits in increasing order
- Count number of trailing zeros in Binary representation of a number using Bitset
- Python | Count unset bits in a range
- Count number of common elements between two arrays by using Bitset and Bitwise operation
- Set all the bits in given range of a number
- Smallest number whose set bits are maximum in a given range
- Subset Sum Queries in a Range using Bitset
- Count Set-bits of number using Recursion
- Count pairs (A, B) such that A has X and B has Y number of set bits and A+B = C
- Count total bits in a number
- Count unset bits of a number
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : AnkitRai01