Set the rightmost unset bit | Python3 implementation to set the rightmost unset bit ; function to find the position of rightmost set bit ; if n = 0 , return 1 ; if all bits of ' n ' are set ; position of rightmost unset bit in ' n ' passing ~ n as argument ; set the bit at position 'pos ; Driver code
import math NEW_LINE def getPosOfRightmostSetBit ( n ) : NEW_LINE INDENT return int ( math . log2 ( n & - n ) + 1 ) NEW_LINE DEDENT def setRightmostUnsetBit ( n ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( ( n & ( n + 1 ) ) == 0 ) : NEW_LINE INDENT return n NEW_LINE DEDENT pos = getPosOfRightmostSetBit ( ~ n ) NEW_LINE DEDENT ' NEW_LINE INDENT return ( ( 1 << ( pos - 1 ) ) n ) NEW_LINE DEDENT n = 21 NEW_LINE print ( setRightmostUnsetBit ( n ) ) NEW_LINE