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:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
In case you wish to attend live classes with industry experts, please refer DSA Live Classes