Algorithm competition entry classic 5.3 sorting and retrieval, algorithm competition entry classic
1/* 2 * assume that you have a four-digit number that is different from each other. Sort all the numbers in ascending order To Get a, and then sort all the numbers in descending order to get B, then replace the original number with a-B and continue the operation. 3 * assume that, starting from 1234, 4321-1234 = 3087, 8730-378 = 8352, and 8532-2358 = 6174 can be obtained in sequence. Interestingly, 7641-1467 = 6174, return to itself. 4 * enter an n-digit number and output the operation sequence until a loop occurs (that is, the new number has been obtained ). The input ensures that up to 1000 integers are generated before the loop. 5 * sample input: 1234 6 * sample output: 1234-> 3087-> 8352-> 6174-> 6174 7 */8 9 # include <stdio. h> 10 # include <string. h> 11 int num [2000], count; 12 13 int get_next (int x) 14 {15 int a, B, n; 16 char s [10]; 17 // convert to string 18 sprintf (s, "% d", x); // for usage instructions, see <common functions> 19 n = strlen (s); // string. h20 // bubble sort 21 for (int I = 0; I <n; I ++) // temporary definition variable, not ANSI C. It is recommended to save the extension. cpp; 22 for (int j = I + 1; j <n; j ++) 23 if (s [I]> s [j]) 24 {25 char t = s [I]; s [I] = s [j]; s [j] = t; 26} 27 sscanf (s, "% d", & B ); // usage can be found at <common functions> 28 // string inversion 29 for (int I = 0; I <n/2; I ++) 30 {31 char t = s [I]; s [I] = s [n-1-i]; s [n-1-i] = t; 32} 33 sscanf (s, "% d ", & a); 34 return a-B; 35} 36 37 int main () 38 {39 scanf ("% d", & num [0]); 40 printf ("% d", num [0]); 41 count = 1; 42 (;;) 43 {44 // generate and output the next number 45 num [count] = get_next (num [count-1]); 46 printf ("-> % d ", num [count]); 47 // search for new values in the array num The number of 48 int found = 0; 49 for (int I = 0; I <count; I ++) 50 if (num [I] = num [count]) {found = 1; break;} 51 // if found, exit the loop 52 if (found) break; 53 count ++; 54} 55 printf ("\ n "); 56 return 0; 57} 58/* Analysis: 59 * Step 1: use the "bubble sort" method to sort the numbers. Compile the get_next function to get the next number. Step 60*2: generate each number one by one and determine whether it has occurred. An array is commonly used. 61 */