Count total set bits in all numbers from 1 to n | Returns count of set bits present in all numbers from 1 to n ; initialize the result ; A utility function to count set bits in a number x ; Driver program
def countSetBits ( n ) : NEW_LINE INDENT bitCount = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT bitCount += countSetBitsUtil ( i ) NEW_LINE DEDENT return bitCount NEW_LINE DEDENT def countSetBitsUtil ( x ) : NEW_LINE INDENT if ( x <= 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT return ( 0 if int ( x % 2 ) == 0 else 1 ) + countSetBitsUtil ( int ( x / 2 ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 4 NEW_LINE print ( " Total ▁ set ▁ bit ▁ count ▁ is " , countSetBits ( n ) ) NEW_LINE DEDENT