题目:
给定任一个各位数字不完全相同的 4 位正整数,如果我们先把 4 个数字按非递增排序,再按非递减排序,然后用第 1 个数字减第 2 个数字,将得到一个新的数字。一直重复这样做,我们很快会停在有“数字黑洞”之称的 6174,这个神奇的数字也叫 Kaprekar 常数。
例如,我们从6767开始,将得到
7766 - 6677 = 1089
9810 - 0189 = 9621
9621 - 1269 = 8352
8532 - 2358 = 6174
7641 - 1467 = 6174
… …
现给定任意 4 位正整数,请编写程序演示到达黑洞的过程。
#include<stdio.h>
#include<math.h>
int main()
{ int n;
scanf("%d",&n);
while(n!=6174)
{
int a[4];
a[0]=n%10;
a[1]=(n%100-n%10)/10;
a[2]=(n%1000-n%100)/100;
a[3]=n/1000;
if(a[0]==a[1]&&a[1]==a[2]&&a[2]==a[3])
{ printf("%d-%d=0000",n,n);
break;
}
//冒泡排序
int temp=0,i=0,j=0;
for(i=0;i<4;i++)
{
for(j=0;j<3-i;j++)
{
if(a[j]<a[j+1])
{
temp=a[j+1];
a[j+1]=a[j];
a[j]=temp;
}
}
}
int result1=0;
for(i=0;i<4;i++)
{
result1+=a[i]*pow(10,i);
}
int b[4];
b[0]=n%10;
b[1]=(n%100-n%10)/10;
b[2]=(n%1000-n%100)/100;
b[3]=n/1000;
for(i=0;i<4;i++)
{
for(j=0;j<3-i;j++)
{
if(b[j]>b[j+1])
{
temp=b[j+1];
b[j+1]=b[j];
b[j]=temp;
}
}
}
int result2=0;
for(i=0;i<4;i++)
{
result2+=b[i]*pow(10,i);
}
int result=0;
result=result2-result1;
if(result1>=1000)
{
printf("%d - %d=%d\n",result2,result1,result);
}
else
{
printf("%d - 0%d=%d\n",result2,result1,result);
}
n=result;
}
return 0;
}