Next greater integer having one more number of set bits | Python3 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
import math NEW_LINE def getFirstSetBitPos ( n ) : NEW_LINE INDENT return ( ( int ) ( math . log ( n & - n ) / math . log ( 2 ) ) + 1 ) - 1 NEW_LINE DEDENT def nextGreaterWithOneMoreSetBit ( n ) : NEW_LINE INDENT pos = getFirstSetBitPos ( ~ n ) NEW_LINE if ( pos > - 1 ) : NEW_LINE INDENT return ( 1 << pos ) | n NEW_LINE DEDENT return ( ( n << 1 ) + 1 ) NEW_LINE DEDENT n = 10 NEW_LINE print ( " Next ▁ greater ▁ integer ▁ = ▁ " , nextGreaterWithOneMoreSetBit ( n ) ) NEW_LINE