PAT (Basic Level) 1019 数字黑洞

题意

对于给定的四位正整数,用全排列中最大的数减最小的数,得到新数字,一直操作,直到达到6174或0000

思路

string模拟即可。要善用一些函数,如sort,stoi,to_string。更多乐趣,详见cppreference

代码

#include <bits/stdc++.h>
using namespace std;
int main() {
	ios::sync_with_stdio(false);
	cin.tie(nullptr);
	cout.tie(nullptr);
	string s;
	cin >> s;
	while (s.size() < 4) s.push_back('0');
	do {
		string s1 = s, s2 = s;
		sort(s1.begin(), s1.end(), greater<char>());
		sort(s2.begin(), s2.end());
		cout << setw(4) << setfill('0') << s1 << " - ";
		cout << setw(4) << setfill('0') << s2 << " = ";
		cout << setw(4) << setfill('0') << stoi(s1) - stoi(s2) << '\n';
		s = to_string(stoi(s1) - stoi(s2));
		while (s.size() < 4) s.push_back('0');
	} while (s != "0000" && s != "6174");
	return 0;
} 	 

HINT

不定时更新更多题解,Basic Level 全部AC代码,详见 link ! ! !

发布了31 篇原创文章 · 获赞 15 · 访问量 762

猜你喜欢

转载自blog.csdn.net/abcdefbrhdb/article/details/104564427