求助一道站外题
  • 板块题目总版
  • 楼主Llc521585Y
  • 当前回复2
  • 已保存回复2
  • 发布时间2021/8/24 17:18
  • 上次更新2023/11/4 09:11:42
查看原帖
求助一道站外题
521585
Llc521585Y楼主2021/8/24 17:18
探索数字宇宙
经验值:0
题目描述 Description
现有一个4位且各个位不完全相同的正整数n,若先将n这个正整数上的 4 个数字递减排序得到一个数a,再按递增排序得到一个数b,然后用a减b,将得到一个新的数字。一直重复,最终相减会得到6174,这个数字通常被黑洞之数。
例如,我们从7252开始,将得到:
7522 - 2257 = 5265
6552 - 2556 = 3996
9963 - 3699 = 6264
6642 - 2466 = 4176
7641 - 1467 = 6174

… …
现给定任意 4 位正整数,请编写程序演示到达黑洞的过程。

输入描述 Input Description
输入一个正整数n

输出描述 Output Description
若 n的 4 位数字全相等,则在一行内输出 n - n = 0000;
否则将计算的每一步在一行内输出,直到 6174 作为差出现,输出格式见样例。注意每个数字按 4 位数格式输出。

样例输入 Sample Input
样例输入16767
样例输入23333
样例输出 Sample Output
样例输出17766 - 6677 = 1089
9810 - 0189 = 9621
9621 - 1269 = 8352
8532 - 2358 = 6174
样例输出23333 - 3333 = 0
数据范围及提示 Data Size & Hint
0<n<=10000
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
const int final_ans=6174;
bool check_yes(int s)
{
	bool jilu[10];
	memset(jilu, 0, sizeof(jilu));
	while(s!=0)
	{
		jilu[s%10]+=1;
		s/=10;
	}
	int cnt=0;
	for(int i=0; i<=9; i++)
		if(jilu[i]!=0)
			cnt++;
	return cnt==1?1:0;
}
void print_sup(int ans)
{
	cout << ans << " - " << ans << " = " << 0;
}
int n;
string change_str(int s)
{
	int len=0;
	char shun[5];
	while(s!=0)
	{
		shun[len++] = char(s%10+'0');
		s/=10;
	}
	sort(shun, shun+4);
	return shun;
}
int cifang(int ds, int ms)
{
	int ans=1;
	for(int i=1; i<=ms; i++)
		ans*=ds;
	return ans;
}
int change_num(string dc)
{
	int f;
	for(int i=0; i<4; i++)
		f = f+cifang(10, 4-i-1) * (int)(dc[i]-'0');
	return f;
}
string change_ni(string s1)
{
	string ans;
	for(int i=s1.size()-1; i>=0;i--)
	{
		ans+=s1[i];
	}
	return ans;
}
int main()
{
	int n;
	cin >> n;
	if(check_yes(n))
	{
		print_sup(n);
		return 0;
	}
	int ans=n;
	while(ans != final_ans)
	{
		string s2 = change_str(ans);	//变成顺序存储
//		s2.erase(4, 1);
		string s1 = change_ni(s2);
//		s1.erase(4, 1);
		int ds=change_num(s2);
		int ds1=change_num(s1);
		cout << ds1 << " - " << ds << " = " << ans-ds << endl;
		ans = ds1-ds;
		if(ans==final_ans)
			return 0;
	}
	return 0;
} 

求改错

2021/8/24 17:18
加载中...