# PAT-1019. Digital black hole

Posted by CBaZ on Sat, 04 Jan 2020 06:21:27 +0100

### Title Description

```Given a 4-digit positive integer with different digits, if we first rank the 4 digits in non increasing order, then rank them in non decreasing order, and then subtract the second digit from the first digit, we will get
A new number. We will soon stop at 6174, the "digital black hole", which is also called Kaprekar constant.

For example, starting with 6767, we will get

7766 - 6677 = 1089
9810 - 0189 = 9621
9621 - 1269 = 8352
8532 - 2358 = 6174
7641 - 1467 = 6174
... ...

Given any 4-bit positive integer, please write a program to demonstrate the process of reaching the black hole.```

### Enter a description:

`Enter to give a positive integer N in a (0, 10000) interval.`

### Output Description:

```If the four digits of N are all equal, output "N-N = 0000" in one line; otherwise, output each step of calculation in one line until 6174 appears as a difference. See the example for the output format. There is no blank line in the middle of each line. Note that each number is in the 4-digit box
Output.```

`6767`

### Output example:

```7766 - 6677 = 1089
9810 - 0189 = 9621
9621 - 1269 = 8352
8532 - 2358 = 6174```

In this paper, we should pay special attention to the boundary conditions, such as the output situation when all four digits are equal. There is no useless information about the subject.

```#include<iostream>
using namespace std;
int a,b,c;
int max()
{
int M = 0;
for (int i = 0; i<4; i++)
{
for (int j = i + 1; j<4; j++)
{
if (a[i]<a[j])
{
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
for (int i = 0; i<4; i++)
{
M = M * 10 + a[i];
}
return M;
}
int min()
{
int N = 0;
for (int i = 0; i<4; i++)
{
for (int j = i + 1; j<4; j++)
{
if (a[i]>a[j])
{
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
for (int i = 0; i<4; i++)
{
N = N * 10 + a[i];
}
return N;
}
int main()
{
int d;
cin >> d;
a = d / 1000;
a = (d / 100) % 10;
a = (d / 10) % 10;
a = d % 10;
if (a == a && a == a && a == a)
cout << a << a << a << a << " - " << a << a << a << a << " = " << "0000" << endl;
else
{
do
{
d = max() - min();
b = max() / 1000;
b = (max() / 100) % 10;
b = (max() / 10) % 10;
b = max() % 10;
c = min() / 1000;
c = (min() / 100) % 10;
c = (min() / 10) % 10;
c = min() % 10;
cout << b << b << b << b << " - " << c << c << c << c << " = ";
a = d / 1000;
a = (d / 100) % 10;
a = (d / 10) % 10;
a = d % 10;
cout << a << a << a << a << endl;
} while (d != 6174);
}
return 0;
}```