Next greater integer having one more number of set bits | function to find the position of rightmost set bit . Returns - 1 if there are no set bits ; function to find the next greater integer ; position of rightmost unset bit of n by passing ~ n as argument ; if n consists of unset bits , then set the rightmost unset bit ; n does not consists of unset bits ; Driver program to test above
function getFirstSetBitPos ( n ) { return ( parseInt ( Math . log ( n & - n ) / Math . log ( 2 ) ) + 1 ) - 1 ; } function nextGreaterWithOneMoreSetBit ( n ) { var pos = getFirstSetBitPos ( ~ n ) ; if ( pos > - 1 ) return ( 1 << pos ) | n ; return ( ( n << 1 ) + 1 ) ; } var n = 10 ; document . write ( " " + nextGreaterWithOneMoreSetBit ( n ) ) ;