Number formed by flipping all bits to the left of 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
def getTotCount ( num ) : NEW_LINE INDENT totCount = 1 NEW_LINE firstCount = 1 NEW_LINE temp = 1 NEW_LINE while ( not ( num & temp ) ) : NEW_LINE INDENT temp = temp << 1 NEW_LINE totCount += 1 NEW_LINE DEDENT firstCount = totCount NEW_LINE temp = num >> totCount NEW_LINE while ( temp ) : NEW_LINE INDENT totCount += 1 NEW_LINE temp = temp >> 1 NEW_LINE DEDENT return totCount , firstCount NEW_LINE DEDENT def flipBitsFromRightMostSetBit ( num ) : NEW_LINE INDENT totbit , firstbit = getTotCount ( num ) NEW_LINE num1 = num ^ ( ( 1 << totbit ) - 1 ) NEW_LINE num1 = num1 ^ ( ( 1 << firstbit ) - 1 ) NEW_LINE return num1 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 120 NEW_LINE print ( flipBitsFromRightMostSetBit ( n ) ) NEW_LINE DEDENT