Given any one of the digits not identical four positive integer, if we first four digits ordered by nonincreasing, then a non-descending order, and then the first number minus the second number, will get a new digital. Has been repeated so doing, we will soon be parked in the "digital black hole," he said 6174
, the magic number is also called Kaprekar constant.
For example, from the 6767
start, will be
7766 - 6677 = 1089
9810 - 0189 = 9621
9621 - 1269 = 8352
8532 - 2358 = 6174
7641 - 1467 = 6174
... ...
Now given any four positive integers, write a program demonstrates the process of reaching the black hole.
Input formats:
Input gives a positive integer in the interval ( N.
Output formats:
If N is equal to 4-bit digital full, then the output line N - N = 0000
; otherwise, the output of each step will be calculated in a row, until 6174
a difference is present, see the sample output format. Note that each digital press 4
output digit format.
Sample Input 1:
6767
Output Sample 1:
7766 - 6677 = 1089
9810 - 0189 = 9621
9621 - 1269 = 8352
8532 - 2358 = 6174
Sample Input 2:
2222
Output Sample 2:
2222 - 2222 = 0000
#include <iostream> #include <algorithm> #include <sstream> using namespace std; void give4(string& ini){ for(int i=0;i<ini.length()-4;i++){ ini+="0"; } } bool cmp(char a,char b){ return a<b;//从小到大 } int toInt(string s){ int sum=0; for(int i=0;i<s.length();i++){ sum=sum*10+(s[i]-'0'); } return sum; } string toStr(int a){ stringstream ss; string s; ss<<a; ss>>s; return s; } int main(){ string ini; cin>>ini; give4(ini); int small,big; while(true){ sort(ini.begin(),ini.end(),cmp); small=toInt(ini); reverse(ini.begin(),ini.end()); big=toInt(ini); printf("%04d - %04d = %04d\n",big,small,(big-small)); if((big-small)==0||(big-small)==6174) break; ini=toStr((big-small)); give4(ini); } system("pause"); return 0; }