Count total set bits in all numbers from 1 to n |
def getSetBitsFromOneToN ( N ) : NEW_LINE INDENT two = 2 NEW_LINE ans = 0 NEW_LINE n = N NEW_LINE while ( n != 0 ) : NEW_LINE INDENT ans += int ( N / two ) * ( two >> 1 ) NEW_LINE if ( ( N & ( two - 1 ) ) > ( two >> 1 ) - 1 ) : NEW_LINE INDENT ans += ( N & ( two - 1 ) ) - ( two >> 1 ) + 1 NEW_LINE DEDENT two <<= 1 ; NEW_LINE n >>= 1 ; NEW_LINE DEDENT return ans NEW_LINE DEDENT