Count number of set bits in a range using bitset | Python3 implementation of above approach ; function for converting binary string into integer value ; 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
N = 32 NEW_LINE def binStrToInt ( binary_str ) : NEW_LINE INDENT length = len ( binary_str ) NEW_LINE num = 0 NEW_LINE for i in range ( length ) : NEW_LINE INDENT num = num + int ( binary_str [ i ] ) NEW_LINE num = num * 2 NEW_LINE DEDENT return num / 2 NEW_LINE DEDENT def GetOne ( s , L , R ) : NEW_LINE INDENT length = len ( s ) ; NEW_LINE bit = s . zfill ( 32 - len ( s ) ) ; NEW_LINE bit = int ( binStrToInt ( bit ) ) NEW_LINE bit <<= ( N - length + L - 1 ) ; NEW_LINE bit >>= ( N - length + L - 1 ) ; NEW_LINE bit >>= ( length - R ) ; NEW_LINE return bin ( bit ) . count ( '1' ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = "01010001011" ; NEW_LINE L = 2 ; R = 4 ; NEW_LINE print ( GetOne ( s , L , R ) ) ; NEW_LINE DEDENT