题目
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
注意输入可能不足4位,需要补0
代码:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
bool cm(const char& c1,const char& c2); //由大到小排序
int To_num(string s); //转换为数字
string dec(string s1,string s2); //字符串形式表述的4位数相减
int main()
{
string s,s1,s2;
int num;
cin>>s;
while(s.size()<4) //补足4位
s+='0';
if(s[0]==s[1]&&s[1]==s[2]&&s[2]==s[3]) //判断是否为全等
{
cout<<s<<" - "<<s<<" = 0000";
return 0;
}
num=To_num(s);
do //模拟循环
{
sort(s.begin(),s.end(),cm);
s1=s;
sort(s.begin(),s.end());
s2=s;
s=dec(s1,s2);
cout<<s1<<" - "<<s2<<" = "<<s<<endl;
num=To_num(s);
}while(num!=6174);
return 0;
}
bool cm(const char& c1,const char& c2)
{
return c1>c2;
}
int To_num(string s) //转为数字
{
return (s[0]-'0')*1000+(s[1]-'0')*100+(s[2]-'0')*10+s[3]-'0';
}
string dec(string s1,string s2) //字符串表示的数字相减
{
string s="0000";
int f=0;
for(int i=3;i>=0;i--)
{
if(s1[i]>=s2[i]+f)
{
s[i]='0'+s1[i]-s2[i]-f;
f=0;
}
else
{
s[i]='0'+s1[i]+10-s2[i]-f;
f=1;
}
}
return s;
}