6174问题

描写叙述:
如果你有一个各位数字互不同样的四位数,把全部的数字从大到小排序后得到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

代码例如以下(1):

#include <iostream>
using namespace std;
int main()
{
	int i,j,t,k,n,b,s;
	int a[4];
	cin>>s;
while(s--) 
{		
       cin>>b;
		int count=1;
		while(b!=6174)
		{ 
			a[0]=(b)%10;
		    a[1]=(b)/10%10;
	    	a[2]=(b)/100%10;
		    a[3]=(b)/1000;
		   for(j=0;j<3;j++)       //j轮比較
			   for(i=0;i<3-j;i++) //3-j次两两比較
            if(a[i]>a[i+1])       //从小到大排列
			{
                    t=a[i];a[i]=a[i+1];a[i+1]=t;
			}
                        k=a[0]*1000+a[1]*100+a[2]*10+a[3]*1;
                        n=a[3]*1000+a[2]*100+a[1]*10+a[0]*1;
					b=n-k;
					//cout<<b<<endl;
					count++; 		
		}
		cout<<count;
		cout<<endl;
	}
	return 0;
}
代码例如以下(2)<pre name="code" class="cpp">#include<stdio.h>
int Test(int m)
{
     int c[4],j,k,temp,a,b;
     	c[0]=(m)%10;
		c[1]=(m)/10%10;
		c[2]=(m)/100%10;
		c[3]=(m)/1000;
     for(j=0;j<3;++j)
        for(k=j+1;k<4;++k)
        {
           if(c[j]<c[k])  //从大到小排序
           {
               temp=c[j];
               c[j]=c[k];
               c[k]=temp;
           }

        }
        a=1000*c[0]+100*c[1]+10*c[2]+c[3];
        b=1000*c[3]+100*c[2]+10*c[1]+c[0];


        return a-b;
}
int main()
{
  int n,m,count;
  int c[4];
  scanf("%d",&n);
 while(n--)
  {
     count=1;
     scanf("%d",&m);

     while(m!=6174)
     {
       m=Test(m);
       count++;
     }
      printf("%d
",count);
  }
   return 0;
}



原文地址:https://www.cnblogs.com/zhchoutai/p/6830240.html