#include <stdio.h>

/**

*a. Find the rightmost two digits where left is less than right

*b. if such pair found

* swap them and from the beginning of right digit of the pair to the end

* swap all the pairs where left is greater than equal to right

*c. else given number is the highest number with the given digits

*/

void swap(int *a, int *b) {

int tmp = *a;

*a = *b;

*b = tmp;

}

int main() {

int n

, digits[256] /*stores the digits in reverse order*/

, numDigits = 0

, i = 1

, newNum = 0;

scanf("%d", &n);

while (n) {

digits[numDigits++] = n % 10;

n /= 10;

}

/*find the first rightmost two digits where left is less than right*/

while (i < numDigits && digits[i] >= digits[i - 1]) i++;

if (i < numDigits) {

/*Swap them*/

swap(digits + i - 1, digits + i);

/*start from the right digit of the pair*/

i -= 2;

/*swap the two digits where left is greater than or equal to right*/

while (i >= 0 && digits[i + 1] >= digits[i]) {

swap(digits + i + 1, digits + i);

i--;

}

for (i = numDigits - 1; i >= 0 ; --i) {

newNum = newNum * 10 + digits[i];

}

printf("next Higher = %d\n", newNum);

} else {

printf("This is the highest\n");

}

return 0;

}

### Like this:

Like Loading...

*Related*

your output for 1357642 is 1357642, but actual output is 1362457