Nearest greater number by interchanging the digits | JAVAscript program to find nearest greater value ; Find all the possible permutation of Value A . ; Convert into Integer ; Find the minimum value of A by interchanging the digit of A and store min1 . ; Swap two string character ; Driver code ; Convert integer value into string to find all the permutation of the number ; count = 1 means number greater than B exists
let min1 = Number . MAX_VALUE ; let count = 0 ; function permutation ( str1 , i , n , p ) { if ( i == n ) { let q = parseInt ( str1 ) ; if ( q - p > 0 && q < min1 ) { min1 = q ; count = 1 ; } } else { for ( let j = i ; j <= n ; j ++ ) { str1 = swap ( str1 , i , j ) ; permutation ( str1 , i + 1 , n , p ) ; str1 = swap ( str1 , i , j ) ; } } return min1 ; } function swap ( str , i , j ) { let ch = str . split ( " " ) ; let temp = ch [ i ] ; ch [ i ] = ch [ j ] ; ch [ j ] = temp ; return ( ch ) . join ( " " ) ; } let A = 213 ; let B = 111 ; let str1 = A . toString ( ) ; let len = str1 . length ; let h = permutation ( str1 , 0 , len - 1 , B ) ; if ( count == 1 ) document . write ( h ) ; else document . write ( - 1 ) ;