Binary representation of next greater number with same number of 1 ' s ▁ and ▁ 0' s | Java program to find next permutation in a binary string . ; 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 program to test above
class GFG { static String nextGreaterWithSameDigits ( char [ ] bnum ) { int l = bnum . length ; int i ; for ( i = l - 2 ; i >= 1 ; i -- ) { if ( bnum [ i ] == '0' && bnum [ i + 1 ] == '1' ) { char ch = bnum [ i ] ; bnum [ i ] = bnum [ i + 1 ] ; bnum [ i + 1 ] = ch ; break ; } } if ( i == 0 ) System . out . println ( " no ▁ greater ▁ number " ) ; int j = i + 2 , k = l - 1 ; while ( j < k ) { if ( bnum [ j ] == '1' && bnum [ k ] == '0' ) { char ch = bnum [ j ] ; bnum [ j ] = bnum [ k ] ; bnum [ k ] = ch ; j ++ ; k -- ; } else if ( bnum [ i ] == '0' ) break ; else j ++ ; } return String . valueOf ( bnum ) ; } public static void main ( String [ ] args ) { char [ ] bnum = "10010" . toCharArray ( ) ; System . out . println ( " Binary ▁ representation ▁ of ▁ next ▁ greater ▁ number ▁ = ▁ " + nextGreaterWithSameDigits ( bnum ) ) ; } }