数字黑洞
#include<iostream>
#include<algorithm>
using namespace std;
int fun(int a[])
{
return a[0]*1000+a[1]*100+a[2]*10+a[3];
}
void fun1(int a[],int x)
{
a[0]=x%10,a[3]=x/1000;
a[1]=x%100/10,a[2]=x%1000/100;
}
void fun2(int x)
{
cout<<x/1000<<x%1000/100<<x%100/10<<x%10;
}
bool cmp(int a,int b)
{
return a>b;
}
int main()
{
int a[4],b[4];
int result,n;
cin>>n;
fun1(a,n),fun1(b,n);
while(1)
{
sort(a,a+4),sort(b,b+4,cmp);
result=fun(b)-fun(a);
if(result==0)
{
cout<<fun(b)<<" - "<<fun(a)<<" = "<<"0000"<<endl;
break;
}
else
{
fun2(fun(b));
cout<<" - ";
fun2(fun(a));
cout<<" = ";
fun2(result);
cout<<endl;
}
if(result==6174)
break;
fun1(a,result),fun1(b,result);
}
}
无注释版
#include<iostream>
#include<algorithm>
using namespace std;
int fun(int a[])
{
return a[0]*1000+a[1]*100+a[2]*10+a[3];
}
void fun1(int a[],int x)
{
a[0]=x%10,a[3]=x/1000;
a[1]=x%100/10,a[2]=x%1000/100;
}
bool cmp(int a,int b)
{
return a>b;
}
int main()
{
int a[4],b[4];
int result,n;
cin>>n;
fun1(a,n),fun1(b,n);
while(1)
{
sort(a,a+4),sort(b,b+4,cmp);
result=fun(b)-fun(a);
if(result==0)
{
cout<<fun(b)<<" - "<<fun(a)<<" = "<<"0000"<<endl;
break;
}
else
printf("%04d - %04d = %04d\n",fun(b),fun(a),result);
if(result==6174)
break;
fun1(a,result),fun1(b,result);
}
}