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
function nextGreaterWithSameDigits ( bnum ) { let l = bnum . length ; let i ; for ( i = l - 2 ; i >= 1 ; i -- ) { if ( bnum [ i ] == ' ' && bnum [ i + 1 ] == ' ' ) { let ch = bnum [ i ] ; bnum [ i ] = bnum [ i + 1 ] ; bnum [ i + 1 ] = ch ; break ; } } if ( i == 0 ) document . write ( " " ) ; let j = i + 2 , k = l - 1 ; while ( j < k ) { if ( bnum [ j ] == ' ' && bnum [ k ] == ' ' ) { let ch = bnum [ j ] ; bnum [ j ] = bnum [ k ] ; bnum [ k ] = ch ; j ++ ; k -- ; } else if ( bnum [ i ] == ' ' ) break ; else j ++ ; } return ( bnum ) . join ( " " ) ; } let bnum = " " . split ( " " ) ; document . write ( " " + " " + nextGreaterWithSameDigits ( bnum ) ) ;