PAT乙题1019. 数字黑洞 (20)

2018/01/26 PAT 共 780 字,约 3 分钟
#include<iostream>
#include<string>
#include<cctype>
#include<vector>
#include<algorithm>
#include<functional>
using namespace std;
int main() {
#ifdef LOCAL
	freopen("d:\\datain.txt", "r", stdin);
	//freopen("d:\\dataout.txt", "w", stdout);
#endif LOCAL
	string n;
	cin >> n;
	n.insert(0, 4 - n.length(), '0');
	bool f = false;
	for (int i = 0; i < n.length(); i++) {
		if (n[0]!=n[i]) { f = true; break; }
	}
	int a, b;
	string t1, t2;
	int n1 = stoi(n);

	if (!f) {
		printf("%d - %d = 0000", n1, n1);
	}
	else {
		do {
			t1 =to_string(n1);
			t1.insert(0, 4 - t1.length(), '0');

			t2 = t1;
			sort(t1.begin(), t1.end(), greater<char>());
			sort(t2.begin(), t2.end());
			//cout << t1 << " " << t2 << endl;

			a = stoi(t1);
			b = stoi(t2);

			printf("%04d - %04d = %04d\n", a, b, a - b);
			n1 = a - b;
		} while (n1 != 6174);

	}
}

Search

    Table of Contents