-
Notifications
You must be signed in to change notification settings - Fork 50
/
dict_order.c
57 lines (47 loc) · 1.12 KB
/
dict_order.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include <stdio.h>
#include <stdlib.h>
/*
* 给定一个正整数,实现一个方法来求出离该整数最近的大于自身的“换位数”.
* 例如 12345 -> 12354
* 12354 -> 12435 12435->12453
*/
#define NUMBER_MAX_DIGITS 10
int main(void) {
char c, tmp;
char num[NUMBER_MAX_DIGITS];
int cLength = 0, i, j, rLocation, bigLoc;
while ((c = getchar()) != '\n') {
num[cLength++] = c;
}
//1.寻找最大逆序
rLocation = cLength - 1;
for (i = cLength - 1; i > 0; i--) {
if (num[i-1] > num[i]) {
rLocation = i - 1;
} else {
break;
}
}
//2.逆序的前一个和逆序中刚好大于它的值互换
bigLoc = rLocation;
for (i = rLocation; i < cLength; i++) {
if (num[i] > num[rLocation - 1] && num[i] < num[bigLoc]) {
bigLoc = i;
}
}
tmp = num[rLocation - 1];
num[rLocation - 1] = num[bigLoc];
num[bigLoc] = tmp;
printf("%s\n", num);
//3.逆序重排为顺序
for (i = rLocation; i < cLength; i++) {
for (j = rLocation; j < cLength - 1 - i + rLocation; j++) {
if (num[j] > num[j+1]) {
tmp = num[j];
num[j] = num[j+1];
num[j+1] = tmp;
}
}
}
printf("%s\n", num);
}