Toggle first and last bits of a number | Java program to 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
import java . io . * ; class GFG { static int takeLandFsetbits ( int n ) { n |= n >> 1 ; n |= n >> 2 ; n |= n >> 4 ; n |= n >> 8 ; n |= n >> 16 ; return ( ( n + 1 ) >> 1 ) + 1 ; } static int toggleFandLbits ( int n ) { if ( n == 1 ) return 0 ; return n ^ takeLandFsetbits ( n ) ; } public static void main ( String args [ ] ) { int n = 10 ; System . out . println ( toggleFandLbits ( n ) ) ; } }