PAT 1069. The Black Hole of Numbers (20)

时间:2021-08-30 22:25:28

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
此题没有什么难度,基本上就是两个可逆的转换:将一串数字(或者一个字符串)转换为一个整数,或者相反,而这两个转换都是很常见的,司空见惯了。对于此题值得注意的是,不要用字符串来处理(用诸如string、atoi,itoa【gcc上好像没有,可以用memset和sprintf代替】),会超时的!!!什么都不说了,按部就班就好了,请看代码:
#include <cstdio>
#include <algorithm>
#include <functional>
#include <vector>
using namespace std; const int blackHole=;
const int digits=; vector<int> int2vec(int n)
{
vector<int> buf(digits,);
for(int i=;i<digits;++i,n/=)
{
buf[i]=n%;
}
return buf;
} int vec2int(vector<int>& vec)
{
int n=;
int radix=;
for(int i=digits-;i>=;--i)
{
n+=radix*vec[i];
radix*=;
}
return n;
} bool beingTheSame(vector<int>& vec)
{
size_t size=vec.size();
for(int i=;i<size;++i)
{
if(vec[]!=vec[i])
return false;
}
return true;
} int repeat(int n)
{
vector<int> vec=int2vec(n);
sort(vec.begin(),vec.end(),greater<int>());
int first=vec2int(vec);
sort(vec.begin(),vec.end());
int second=vec2int(vec);
int difference=first-second;
printf("%.4d - %.4d = %.4d\n",first,second,difference);
return difference;
}
int _tmain(int argc, _TCHAR* argv[])
{
freopen("1069.txt","r",stdin);
int n;
scanf("%d",&n);
vector<int> vec=int2vec(n);
if(beingTheSame(vec))
{
printf("%.4d - %.4d = 0000\n",n,n);
return ;
}
n=repeat(n);
while(blackHole!=n)
{
n=repeat(n);
}
return ;
}