51nod 2020 排序相减

2020 排序相减 
题目来源: syu练习题
基准时间限制:1 秒 空间限制:131072 KB 分值: 5  难度:1级算法题
 收藏
 关注

“排序相减”操作是指对于任意一个四位数n,将四个数字分别进行顺序排序和逆序排序,得到两个数取相减后结果的绝对值n1,然后继续将n1中的四个数字进行顺序排序和逆序排序,得到两个数取相减后结果的绝对值n2,以此类推,最后总会得到一个数字黑洞,无法跳出。

 

例如:样例2中4176 = 6532 - 2356

Input
第一行输入一个整数T,表示数据组数(1 
    
Output
对于每组数据,输出对于开始的数据n在第k次“排序相减”后结果绝对值。
Input示例
2
1234 2
3562 1
Output示例
8352
4176

这里我用了采用了字符串处理数据,方便;

#include
#include
#include
#include
#include
using namespace std;
int main()
{
	int n;
	int t;
	int k;
	scanf("%d",&t);
	while(t--)
	{
		string s,ss;
		cin>>s>>k;
		while(k--)
		{
			sort(s.begin(),s.end());
			ss=s;
			reverse(ss.begin(),ss.end());
			int num1=atoi(s.c_str());
			int num2=atoi(ss.c_str());
			int num3=abs(num2-num1);
			//printf("%d\n",num3);
			s[3]=num3%10+48;//位序注意一下
			s[2]=num3/10%10+48;
			s[1]=num3/100%10+48;
			s[0]=num3/1000+48;
		}
		//最后输出变回int,不然有的字符串有前导0 
		cout<

你可能感兴趣的:(1级算法题)