PAT 1069. The Black Hole of Numbers (20)

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=6174;
const int digits=4;

vector<int> int2vec(int n)
{
    vector<int> buf(digits,0);
    for(int i=0;i<digits;++i,n/=10)
    {
        buf[i]=n%10;
    }
    return buf;
}

int vec2int(vector<int>& vec)
{
    int n=0;
    int radix=1;
    for(int i=digits-1;i>=0;--i)
    {
        n+=radix*vec[i];
        radix*=10;
    }
    return n;
}

bool beingTheSame(vector<int>& vec)
{
    size_t size=vec.size();
    for(int i=1;i<size;++i)
    {
        if(vec[0]!=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
",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);
        return 0;
    }
    n=repeat(n);
    while(blackHole!=n)
    {
        n=repeat(n);
    }
    return 0;
}
View Code
原文地址:https://www.cnblogs.com/wwblog/p/3704529.html