For any 4-digit integer except the ones with all the digits being the same, if we sort the digits in non-increasing order first, and then in non-decreasing order, a new number can be obtained by taking the second number from the first one. Repeat in this manner we will soon end up at the number 6174 -- the "black hole" of 4-digit numbers. This number is named Kaprekar Constant.
For example, start from 6767, we'll get:
7766 - 6677 = 1089
9810 - 0189 = 9621
9621 - 1269 = 8352
8532 - 2358 = 6174
7641 - 1467 = 6174
... ...
Given any 4-digit number, you are supposed to illustrate the way it gets into the black hole.
Input Specification:
Each input file contains one test case which gives a positive integer N in the range (0, 10000).
Output Specification:
If all the 4 digits of N are the same, print in one line the equation "N - N = 0000". Else print each step of calculation in a line until 6174 comes out as the difference. All the numbers must be printed as 4-digit numbers.
Sample Input 1:
6767
Sample Output 1:
7766 - 6677 = 1089 9810 - 0189 = 9621 9621 - 1269 = 8352 8532 - 2358 = 6174
Sample Input 2:
2222
Sample Output 2:
2222 - 2222 = 0000
1 #include<cstdio> 2 #include<iostream> 3 #include<algorithm> 4 using namespace std; 5 bool cmp1(int a, int b){ 6 return a < b; 7 } 8 bool cmp2(int a, int b){ 9 return a > b; 10 } 11 void numSort(int n, int &r1, int &r2){ 12 int temp[20]; 13 int i = 0; 14 r1 = 0; r2 = 0; 15 do{ 16 temp[i++] = n % 10; 17 n = n / 10; 18 }while(n != 0 || i < 4); 19 sort(temp, temp + i, cmp1); 20 for(int j = 0, P = 1; j < i; j++){ 21 r1 = r1 + P * temp[j]; 22 P = P * 10; 23 } 24 sort(temp, temp + i, cmp2); 25 for(int j = 0, P = 1; j < i; j++){ 26 r2 = r2 + P * temp[j]; 27 P = P * 10; 28 } 29 } 30 int main(){ 31 int N, r1, r2, ans; 32 scanf("%d", &N); 33 numSort(N, r1, r2); 34 do{ 35 ans = r1 - r2; 36 printf("%04d - %04d = %04d ", r1, r2, ans); 37 numSort(ans, r1, r2); 38 }while(ans != 6174 && ans != 0); 39 cin >> N; 40 return 0; 41 }
总结:
1、注意在int转换为num[ ]数组时,如果不够四位,应补全成四位,否则答案会出错。(15应转换为0015和1500,而不是15和50)。