Count set bits in a range | Function to get no of set bits in the binary representation of 'n ; function to count set bits in the given range ; calculating a number ' num ' having ' r ' number of bits and bits in the range l to r are the only set bits ; returns number of set bits in the range ' l ' to ' r ' in 'n ; Driver program to test above
' NEW_LINE def countSetBits ( n ) : NEW_LINE INDENT count = 0 NEW_LINE while ( n ) : NEW_LINE INDENT n &= ( n - 1 ) NEW_LINE count = count + 1 NEW_LINE DEDENT return count NEW_LINE DEDENT def countSetBitsInGivenRange ( n , l , r ) : NEW_LINE INDENT num = ( ( 1 << r ) - 1 ) ^ ( ( 1 << ( l - 1 ) ) - 1 ) NEW_LINE DEDENT ' NEW_LINE INDENT return countSetBits ( n & num ) NEW_LINE DEDENT n = 42 NEW_LINE l = 2 NEW_LINE r = 5 NEW_LINE ans = countSetBitsInGivenRange ( n , l , r ) NEW_LINE print ( ans ) NEW_LINE