Binary representation of next greater number with same number of 1 ' s ▁ and ▁ 0' s | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; string nextGreaterWithSameDigits ( string bnum ) { int l = bnum . size ( ) ; int i ; for ( int i = l - 2 ; i >= 1 ; i -- ) { if ( bnum . at ( i ) == '0' && bnum . at ( i + 1 ) == '1' ) { char ch = bnum . at ( i ) ; bnum . at ( i ) = bnum . at ( i + 1 ) ; bnum . at ( i + 1 ) = ch ; break ; } } if ( i == 0 ) " no ▁ greater ▁ number " ; int j = i + 2 , k = l - 1 ; while ( j < k ) { if ( bnum . at ( j ) == '1' && bnum . at ( k ) == '0' ) { char ch = bnum . at ( j ) ; bnum . at ( j ) = bnum . at ( k ) ; bnum . at ( k ) = ch ; j ++ ; k -- ; } else if ( bnum . at ( i ) == '0' ) break ; else j ++ ; } return bnum ; } int main ( ) { string bnum = "10010" ; cout << " Binary ▁ representation ▁ of ▁ next ▁ greater ▁ number ▁ = ▁ " << nextGreaterWithSameDigits ( bnum ) ; return 0 ; }