解析:1、排序;2、9999 0 1000 5 6174 0
#include<cstdio>
#include<algorithm>#include<iostream>
using namespace std;
int main()
{
int n,a[4];
while(cin>>n&&n!=0)
{
int count=0;
while(n!=6174)
{
int m=0,p=0,tmp=1000;
//拆分四位数
for(int i=0;i<4;i++)
{if(n<tmp)a[i]=0;
else
{a[i]=n%10;
n/=10;}
tmp=tmp/10;
}
//n=9999时,输出0
if(a[0]==a[1]&&a[1]==a[2]&&a[2]==a[3])break;
//排序,当n=1989时,序列应为1899,不能用sort()
for(int i=0;i<3;i++)
{for(int j=i+1;j<4;j++)
{
if(a[j]<a[i])
{
int temp=a[j];
a[j]=a[i];
a[i]=temp; }
}
}
// 重新整合成新的四位数
for(int i=0;i<4;i++)m=m*10+a[i];
for(int i=3;i>=0;i--)p=p*10+a[i];n=p-m;
count++;
}
cout<<count<<endl;
}
return 0;
}