Binary representation of next greater number with same number of 1 ' s ▁ and ▁ 0' s | Function to find the next greater number with same number of 1 ' s ▁ and ▁ 0' s ; locate first ' i ' from end such that bnum [ i ] == '0' and bnum [ i + 1 ] == '1' swap these value and break ; if no swapping performed ; Since we want the smallest next value , shift all 1 ' s ▁ at ▁ the ▁ end ▁ in ▁ the ▁ binary ▁ ▁ substring ▁ starting ▁ from ▁ index ▁ ' i + 2 ; special case while swapping if '0' occurs then break ; required next greater number ; Driver code
def nextGreaterWithSameDigits ( bnum ) : NEW_LINE INDENT l = len ( bnum ) NEW_LINE bnum = list ( bnum ) NEW_LINE for i in range ( l - 2 , 0 , - 1 ) : NEW_LINE INDENT if ( bnum [ i ] == '0' and bnum [ i + 1 ] == '1' ) : NEW_LINE INDENT ch = bnum [ i ] NEW_LINE bnum [ i ] = bnum [ i + 1 ] NEW_LINE bnum [ i + 1 ] = ch NEW_LINE break NEW_LINE DEDENT DEDENT if ( i == 0 ) : NEW_LINE INDENT return " no ▁ greater ▁ number " NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT j = i + 2 NEW_LINE k = l - 1 NEW_LINE while ( j < k ) : NEW_LINE INDENT if ( bnum [ j ] == '1' and bnum [ k ] == '0' ) : NEW_LINE INDENT ch = bnum [ j ] NEW_LINE bnum [ j ] = bnum [ k ] NEW_LINE bnum [ k ] = ch NEW_LINE j += 1 NEW_LINE k -= 1 NEW_LINE DEDENT elif ( bnum [ i ] == '0' ) : NEW_LINE INDENT break NEW_LINE DEDENT else : NEW_LINE INDENT j += 1 NEW_LINE DEDENT DEDENT return bnum NEW_LINE DEDENT bnum = "10010" NEW_LINE print ( " Binary ▁ representation ▁ of ▁ next ▁ greater ▁ number ▁ = ▁ " , * nextGreaterWithSameDigits ( bnum ) , sep = " " ) NEW_LINE