Nearest greater number by interchanging the digits | C ++ 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 . ; Driver code ; Convert integer value into string to find all the permutation of the number ; count = 1 means number greater than B exists
#include <bits/stdc++.h> NEW_LINE using namespace std ; int min1 = INT_MAX ; int _count = 0 ; int permutation ( string str1 , int i , int n , int p ) { if ( i == n ) { int q = stoi ( str1 ) ; if ( q - p > 0 && q < min1 ) { min1 = q ; _count = 1 ; } } else { for ( int j = i ; j <= n ; j ++ ) { swap ( str1 [ i ] , str1 [ j ] ) ; permutation ( str1 , i + 1 , n , p ) ; swap ( str1 [ i ] , str1 [ j ] ) ; } } return min1 ; } int main ( ) { int A = 213 ; int B = 111 ; string str1 = to_string ( A ) ; int len = str1 . length ( ) ; int h = permutation ( str1 , 0 , len - 1 , B ) ; _count ? cout << h << endl : cout << -1 << endl ; return 0 ; }