NYOJ 57 6174问题

啊哈!初次知道6174,还是在高中时,一本科普书上讲的。

作为回顾。就把这道题AC了。

水题,只是去掉以下的凝视。能够非常直观的看到过程。

最后!!!为什么我用memset函数总是忘写#include<cstring>头文件!

!!


时间限制:1000 ms  |  内存限制:65535 KB
难度:2
描写叙述

如果你有一个各位数字互不同样的四位数。把全部的数字从大到小排序后得到a,从小到大后得到b,然后用a-b替换原来这个数。而且继续操作。

比如,从1234出发,依次能够得到4321-1234=3087、8730-378=8352、8532-2358=6174,又回到了它自己!

如今要你写一个程序来推断一个四位数经过多少次这种操作能出现循环,而且求出操作的次数

比方输入1234运行顺序是1234->3087->8352->6174->6174,输出是4

输入
第一行输入n,代表有n组測试数据。
接下来n行每行都写一个各位数字互不同样的四位数
输出
经过多少次上面描写叙述的操作才干出现循环
例子输入
1
1234
例子输出
4



#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;

int ans[4];

bool cmp(int lhs, int rhs)
{
	return lhs>rhs;
}

int mysort(int x,int s)
{
	int i,j;
	memset(ans,0,sizeof(ans));
	for(i=0,j=10000;i<4;i++)
	{
		j/=10;
		ans[i]=x/j%10;
	}
	
	if(s)
		sort(ans,ans+4,cmp);
	else
		sort(ans,ans+4);
/*

	for(i=0;i<4;i++)
		cout<<ans[i]<<" ";
	cout<<endl;

*/
	x=0;
	for(i=0,j=10000;i<4;i++)
	{
		j/=10;
		x+=ans[i]*j;
	}

	return x;
}

int main()
{
	int n,m,lhs,rhs,tmd;
	cin>>n;
	while(n--)
	{
		cin>>m;
		tmd=1;
		while(m!=6174)
		{
			lhs=mysort(m,0);	//升序
			rhs=mysort(m,1);	//降序
			m=rhs-lhs;
			++tmd;
		}
		cout<<tmd<<endl;
	}
	return 0;
}


原文地址:https://www.cnblogs.com/lcchuguo/p/5387246.html