Count total set bits in all numbers from range L to R | Function to count set bit in range ; Count variable ; Find the set bit in Nth number ; If last bit is set ; Left sift by one bit ; Return count ; Driver Code ; Given range L and R ; Function call
def countSetBits ( L , R ) : NEW_LINE INDENT count = 0 ; NEW_LINE for i in range ( L , R + 1 ) : NEW_LINE INDENT n = i ; NEW_LINE while ( n > 0 ) : NEW_LINE INDENT count += ( n & 1 ) ; NEW_LINE n = n >> 1 ; NEW_LINE DEDENT DEDENT return count ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT L = 3 ; R = 5 ; NEW_LINE print ( " Total ▁ set ▁ Bit ▁ count ▁ is ▁ " , countSetBits ( L , R ) ) ; NEW_LINE DEDENT