Count number of set bits in a range using bitset | C ++ implementation of above approach ; function to count number of 1 's using bitset ; Converting the string into bitset ; Bitwise operations Left shift ; Right shifts ; return count of one in [ L , R ] ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define N  32 NEW_LINE int GetOne ( string s , int L , int R ) { int len = s . length ( ) ; bitset < N > bit ( s ) ; bit <<= ( N - len + L - 1 ) ; bit >>= ( N - len + L - 1 ) ; bit >>= ( len - R ) ; return bit . count ( ) ; } int main ( ) { string s = "01010001011" ; int L = 2 , R = 4 ; cout << GetOne ( s , L , R ) ; return 0 ; }