PAT (Advanced Level) Practice 1069 The Black Hole of Numbers (20分)

1.题目

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,10​4​​).

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

2.题目分析

PAT (Basic Level) Practice 1019 数字黑洞 (20分) (string、int转换+sort排序)

3.代码

#include<iostream>
#include<algorithm>
#include<string>
#include<cstring>
#include<sstream>
#include<functional>
using namespace std;
int main()
{
	string number;	
	cin >> number;
	
	string min = number;
	string max = number;

	while (1)
	{
			min = number;
			max = number;
			while (min.length() < 4)
				min.append("0");
			while (max.length() < 4)
				max.append("0");
		sort(min.begin(), min.end(), less<char>());
		sort(max.begin(), max.end(), greater<char>());
		int minn = 0, maxx = 0;
		stringstream ss;
		ss << min;
		ss >> minn;
		stringstream ss2;
		ss2 << max;
		ss2 >> maxx;
		int numberr = maxx - minn;
		if (numberr == 0)
		{
			cout << max << ' ' << '-' << ' ' << min << ' ' << '=' << ' ' << "0000" << endl; break;
		}
		stringstream ss3;
		ss3 << (maxx - minn);
		ss3 >> number;
		for (int i = number.length(); i < 4; i++)
			number = "0" + number;
		cout << max << ' ' << '-' << ' ' << min << ' ' << '=' << ' ' << number << endl;
		if (number == "6174")break;
	}
}
原文地址:https://www.cnblogs.com/Jason66661010/p/12788819.html