Number formed by flipping all bits to the left of rightmost set bit | Java program to find the integer formed after flipping all bits to the left of the rightmost set bit ; Function to get the total count ; Moving until we get the rightmost set bit ; To get total number of bits in a number ; Function to find the integer formed after flipping all bits to the left of the rightmost set bit ; Find the total count of bits and the rightmost set bit ; XOR given number with the number which has is made up of only totbits set ; To avoid flipping the bits to the right of the set bit , take XOR with the number made up of only set firstbits ; Driver Code
import java . util . * ; class GFG { static int totCount ; static int firstCount ; static void getTotCount ( int num ) { totCount = 1 ; firstCount = 1 ; int temp = 1 ; while ( ( num & temp ) == 0 ) { temp = temp << 1 ; totCount += 1 ; } firstCount = totCount ; temp = num >> totCount ; while ( temp != 0 ) { totCount += 1 ; temp = temp >> 1 ; } } static int flipBitsFromRightMostSetBit ( int num ) { getTotCount ( num ) ; int num1 = num ^ ( ( 1 << totCount ) - 1 ) ; num1 = num1 ^ ( ( 1 << firstCount ) - 1 ) ; return num1 ; } public static void main ( String [ ] args ) { int n = 120 ; System . out . println ( flipBitsFromRightMostSetBit ( n ) ) ; } }