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 is obtained by taking the second number from the first one. Repeat in this manner we'll soon end up at the number 6174-the "black hole" of 4-digit numbers. This 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, your is supposed to illustrate the the-it gets into the black hole.
Input Specification:
Each input file contains one test case which gives a positive an integer N in the range (0, 10000).
Output Specification:
If all the 4 digits of N is 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 is 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
Pit point 1, the number should be four bit 2, if the difference between the next equation is not equal to the last result, and then jump out of the words, then need to judge, is not the first output. For example, input 6174, the result is equal to 6174, then will not output, directly jump out.
1#include <iostream>2 3#include <algorithm>4 5#include <string>6 7#include <sstream>8 9#include <iomanip>Ten One using namespacestd; A - - the inta1[5]; - - inta2[5]; - + - + intbb[ +]; A at - - BOOLCMP1 (intAintb) - - { - in returnA>b; - to } + - the * BOOLCMP2 (intAintb) $ Panax Notoginseng { - the returna<b; + A } the + - $ intMain () $ - { - the stringN; - Wuyi inti; the - Wu - while(cin>>N) About $ { - - - A inttt,c1,c2; + the StringStream SS1; - $ss1<<N; the theSs1>>tt; the the - inI=0; the the BOOLFir=true; About the while(true) the the { + - the Bayi stringSS; the the StringStream SS2; - -Ss2<<setfill ('0') <<SETW (4) <<tt; the theSs2>>SS; the the - the for(i=0; I<ss.length (); i++) the the {94 thea1[i]=ss[i]-'0'; the thea2[i]=A1[i];98 About } - 101 102 103Sort (a1,a1+ss.length (), CMP1);104 theSort (a2,a2+ss.length (), CMP2);106 107 108 109c1=0; C2=0; the 111 for(i=0; I<ss.length (); i++) the 113 { the theC1=c1*Ten+A1[i]; the 117c2=c2*Ten+A2[i];118 119 } - 121 122 123 124 the if(C1-c2==tt&&!fir) Break;126 127 Else - 129 the 131 { the 133Fir=false;134 135Cout<<setfill ('0') <<SETW (4) <<c1<<" - "<<setfill ('0') <<SETW (4) <<c2<<" = "<<setfill ('0') <<SETW (4) <<c1-c2<<Endl;136 137Tt=c1-C2;138 139 } $ 141 } 142 143 }144 145 return 0;146 147 }148 149
View Code
The Black Hole of Numbers (Strtoint+inttostr+sort)