1/* 2 * Main. C 3*1019. digital black hole 4 * created on: August 31, 2014 5 * Author: boomkeeper 6 ******** part through ******** 7 */8 9 # include <stdio. h> 10 # include <stdlib. h> Each digit of the 11 12/* 13 * sorted integer 14 * SRC [4]: original array 15 * dstdown [4]: descending sorting result 16 * dstup [4]: ascending sorting result 17 */18 void sort (INT dstup [4], int dstdown [4], int SRC [4]) {19 20 int I, j; 21 int temp; 22 // value 23 for (I = 0; I <4; I ++) {24 dstup [I] = SRC [I]; 25 dstdown [I] = SRC [I]; 26} 27/ /Sort, up 28 for (I = 0; I <4; I ++) {29 for (j = 0; j <4-i-1; j ++) {30 if (dstup [J]> dstup [J + 1]) {31 temp = dstup [J]; 32 dstup [J] = dstup [J + 1]; 33 dstup [J + 1] = temp; 34} 35} 36} 37 // sort, down 38 for (I = 0; I <4; I ++) {39 for (j = 0; j <4-i-1; j ++) {40 if (dstdown [J] <dstdown [J + 1]) {41 temp = dstdown [J]; 42 dstdown [J] = dstdown [J + 1]; 43 dstdown [J + 1] = temp; 44} 45} 46} 47} 48 49/* 50 * split the numbers of Integers to sort 51 * digits: num [3] 52*10: num [2] 5 3 * hundred bits: num [1] 54 * thousand bits: num [0] 55 */56 void split (int n, int num [4]) {57 58 num [3] = n % 10; 59 N/= 10; 60 num [2] = n % 10; 61 N/= 10; 62 num [1] = n % 10; 63 N/= 10; 64 num [0] = N; 65} 66 67/* 68 * get the new 4-digit integer after sorting, do the difference, and return the result s 69 */70 int kaprebar (INT temp) {71 72 int num1 [4] = {0}, num2 [4] = {0}, num3 [4]; // store the numbers 73 int num_1 and num_2 respectively. // values 75 split (temp, num3) and 76 sort (num2, num1, num3); 77 78 // do the difference 79 num_1 = num1 [0] * 1000 + num1 [1] * 100 + num1 [2] * 10 + num1 [3]; 80 num_2 = num2 [0] * 1000 + num2 [1] * 100 + num2 [2] * 10 + num2 [3]; 81 temp = num_1-num_2; 82 If (temp = 0) {83 printf ("% 04d-% 04d = % 04d \ n", num_1, num_2, temp); 84 exit (0 ); 85} else {86 printf ("% 04d-% 04d = % 04d \ n", num_1, num_2, temp); 87} 88 // return Return Difference 89 return temp; 90} 91 92 int main (void) {93 94 int N; // The N 95 96 scanf ("% 4D", & N); 97 int temp = N; 98 99 while (temp! = 6174) {100 temp = kaprebar (temp); 101} 102 103 return 0; 104}
Question link:
Http://pat.zju.edu.cn/contests/pat-b-practise/1019
.
* 1019. Digital Black Hole