NYOJ:57-6174问题

来源:互联网 发布:空间大师设计软件 编辑:程序博客网 时间:2024/05/18 11:47

6174问题
时间限制: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 num[4];int mysort(int x,int k);bool compare(int a,int b);int main(){    int n,m,lnum,snum,countnum;    cin>>n;    while(n--)    {        cin>>m;        countnum=1;        while(m!=6174)        {            lnum=mysort(m,1);//升序            snum=mysort(m,0);//降序            m=snum-lnum;            countnum++;        }        cout<<countnum<<endl;    }    return 0;}bool compare(int a,int b){    return a>b;}int mysort(int x,int k){    int i,j;    memset(num,0,sizeof(num));    for(i=0,j=10000; i<4; i++)    {        j=j/10;        num[i]=x/j%10;    }    if(k)        sort(num,num+4);    else        sort(num,num+4,compare);    x=0;    for(i=0,j=10000; i<4; i++)    {        j=j/10;        x=x+num[i]*j;    }    return x;}
原创粉丝点击