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
< ? php function takeLandFsetbits ( $ n ) { $ n |= $ n >> 1 ; $ n |= $ n >> 2 ; $ n |= $ n >> 4 ; $ n |= $ n >> 8 ; $ n |= $ n >> 16 ; return ( ( $ n + 1 ) >> 1 ) + 1 ; } function toggleFandLbits ( int $ n ) { if ( $ n == 1 ) return 0 ; return $ n ^ takeLandFsetbits ( $ n ) ; } $ n = 10 ; echo toggleFandLbits ( $ n ) ; ? >