Next greater integer having one more number of set bits | Java implementation to find the next greater integer with 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 code
class GFG { static int getFirstSetBitPos ( int n ) { return ( ( int ) ( Math . log ( n & - n ) / Math . log ( 2 ) ) + 1 ) - 1 ; } static int nextGreaterWithOneMoreSetBit ( int n ) { int pos = getFirstSetBitPos ( ~ n ) ; if ( pos > - 1 ) return ( 1 << pos ) | n ; return ( ( n << 1 ) + 1 ) ; } public static void main ( String [ ] args ) { int n = 10 ; System . out . print ( " Next ▁ greater ▁ integer ▁ = ▁ " + nextGreaterWithOneMoreSetBit ( n ) ) ; } }