Next higher number using atmost one swap operation | C ++ implementation to find the next higher number using atmost one swap operation ; function to find the next higher number using atmost one swap operation ; to store the index of the largest digit encountered so far from the right ; to store the index of rightmost digit which has a digit greater to it on its right side ; finding the ' index ' of rightmost digit which has a digit greater to it on its right side ; required digit found , store its ' index ' and break ; if no such digit is found which has a larger digit on its right side ; to store the index of the smallest digit greater than the digit at ' index ' and right to it ; finding the index of the smallest digit greater than the digit at ' index ' and right to it ; swapping the digits ; required number ; Driver program to test above
#include <bits/stdc++.h> NEW_LINE using namespace std ; string nxtHighUsingAtMostOneSwap ( string num ) { int l = num . size ( ) ; int posRMax = l - 1 ; int index = -1 ; for ( int i = l - 2 ; i >= 0 ; i -- ) { if ( num [ i ] >= num [ posRMax ] ) posRMax = i ; else { index = i ; break ; } } if ( index == -1 ) return " Not ▁ Possible " ; int greatSmallDgt = -1 ; for ( int i = l - 1 ; i > index ; i -- ) { if ( num [ i ] > num [ index ] ) { if ( greatSmallDgt == -1 ) greatSmallDgt = i ; else if ( num [ i ] <= num [ greatSmallDgt ] ) greatSmallDgt = i ; } } char temp = num [ index ] ; num [ index ] = num [ greatSmallDgt ] ; num [ greatSmallDgt ] = temp ; return num ; } int main ( ) { string num = "218765" ; cout << " Original ▁ number : ▁ " << num << endl ; cout << " Next ▁ higher ▁ number : ▁ " << nxtHighUsingAtMostOneSwap ( num ) ; return 0 ; }