Toggle first and last bits of a number | Returns a number which has same bit count as n and has only first and last bits as set . ; set all the bit of the number ; Adding one to n now unsets all bits and moves MSB to one place . Now we shift the number by 1 and add 1. ; if number is 1 ; take XOR with first and last set bit number ; Driver code
def takeLandFsetbits ( n ) : NEW_LINE INDENT n = n | n >> 1 NEW_LINE n = n | n >> 2 NEW_LINE n = n | n >> 4 NEW_LINE n = n | n >> 8 NEW_LINE n = n | n >> 16 NEW_LINE return ( ( n + 1 ) >> 1 ) + 1 NEW_LINE DEDENT def toggleFandLbits ( n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT return n ^ takeLandFsetbits ( n ) NEW_LINE DEDENT n = 10 NEW_LINE print ( toggleFandLbits ( n ) ) NEW_LINE