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.

 

Input example:

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[4],b[4],c[4];
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[0] = d / 1000;
	a[1] = (d / 100) % 10;
	a[2] = (d / 10) % 10;
	a[3] = d % 10;
	if (a[0] == a[1] && a[1] == a[2] && a[2] == a[3])
		cout << a[0] << a[1] << a[2] << a[3] << " - " << a[0] << a[1] << a[2] << a[3] << " = " << "0000" << endl;
	else
	{
		do
		{
			d = max() - min();
			b[0] = max() / 1000;
			b[1] = (max() / 100) % 10;
			b[2] = (max() / 10) % 10;
			b[3] = max() % 10;
			c[0] = min() / 1000;
			c[1] = (min() / 100) % 10;
			c[2] = (min() / 10) % 10;
			c[3] = min() % 10;
			cout << b[0] << b[1] << b[2] << b[3] << " - " << c[0] << c[1] << c[2] << c[3] << " = ";
			a[0] = d / 1000;
			a[1] = (d / 100) % 10;
			a[2] = (d / 10) % 10;
			a[3] = d % 10;
			cout << a[0] << a[1] << a[2] << a[3] << endl;
		} while (d != 6174);
	}
	return 0;
}