PTA_ B _1019 digital Black Hole (C ++ _ Analog)

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," said the 6174, the magic number is also called Kaprekar constant.

For example, we start from 6767, 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 given within a positive integer (0, 10 4) section N.

Output formats:

If N is equal to 4-bit digital full, the output in line N - N = 0000; otherwise, the output of each step will be calculated in a row, as a difference occurs until 6174, see sample output format. Note that each of the 4 bits output in digital 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

Code

#include<bits/stdc++.h>
using namespace std;
string n;
bool cmp1(char a, char b)
{
    return a > b;
}
bool cmp2(char a, char b)
{
    return a < b;
}
void bu()
{
    if (n.size() < 4)
        for (int i = n.size(); i < 4; i++)
            n += '0';
}
int main()
{
    cin >> n;
    while (1)
    {
        bu();
        sort(n.begin(), n.end(), cmp1);
        int a = stoi(n);
        sort(n.begin(), n.end(), cmp2);
        int b = stoi(n);
        int temp = a - b;
        n = to_string(temp);
        printf("%04d - %04d = %04d\n", a, b, temp);
        if (temp == 0 || temp == 6174)
            break;
    }
    return 0;
}
Published 228 original articles · won praise 30 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_43510916/article/details/104351286