Count total set bits in all numbers from range L to R | Function to count set bits in x ; Base Case ; Recursive Call ; Function that returns count of set bits present in all numbers from 1 to N ; Initialize the result ; Return the setbit count ; Driver Code ; Given L and R ; Function Call
def countSetBitsUtil ( x ) : NEW_LINE INDENT if ( x < 1 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( x % 2 == 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT else : NEW_LINE INDENT return 1 + ( countSetBitsUtil ( x / 2 ) ) ; NEW_LINE DEDENT DEDENT def countSetBits ( L , R ) : NEW_LINE INDENT bitCount = 0 ; NEW_LINE for i in range ( L , R + 1 ) : NEW_LINE INDENT bitCount += countSetBitsUtil ( i ) ; NEW_LINE DEDENT return bitCount ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT L = 3 ; NEW_LINE R = 5 ; NEW_LINE print ( " Total ▁ set ▁ bit ▁ count ▁ is ▁ " , countSetBits ( L , R ) ) ; NEW_LINE DEDENT