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
function getPosOfRightmostSetBit ( n ) { return ( ( Math . log10 ( n & - n ) ) / ( Math . log10 ( 2 ) ) ) + 1 ; } function setRightmostUnsetBit ( n ) { if ( n == 0 ) return 1 ; if ( ( n & ( n + 1 ) ) == 0 ) return n ; let pos = getPosOfRightmostSetBit ( ~ n ) ; return ( ( 1 << ( pos - 1 ) ) n ) ; } let n = 21 ; document . write ( setRightmostUnsetBit ( n ) ) ;