7-44 黑洞數 (20分)
黑洞數也稱為陷阱數,又稱“Kaprekar問題”,是一類具有奇特轉換特性的數。
任何一個各位數字不全相同的三位數,經有限次“重排求差”操作,總會得到495。最后所得的495即為三位黑洞數。所謂“重排求差”操作即組成該數的數字重排后的最大數減去重排后的最小數。(6174為四位黑洞數。)
例如,對三位數207:
- 第1次重排求差得:720 - 27 = 693;
- 第2次重排求差得:963 - 369 = 594;
- 第3次重排求差得:954 - 459 = 495;
以后會停留在495這一黑洞數。如果三位數的3個數字全相同,一次轉換后即為0。
任意輸入一個三位數,編程給出重排求差的過程。
輸入格式:
輸入在一行中給出一個三位數。
輸出格式:
按照以下格式輸出重排求差的過程:
序號: 數字重排后的最大數 - 重排后的最小數 = 差值
序號從1開始,直到495出現在等號右邊為止。
輸入樣例:
123
輸出樣例:
1: 321 - 123 = 198
2: 981 - 189 = 792
3: 972 - 279 = 693
4: 963 - 369 = 594
5: 954 - 459 = 495
#include<stdio.h>
int min1(int n)
{
int a[3];
int temp;
int min;
int i=0;
int j=0;
int max=0;
if(n%111==0)
return 0;
while(n)
{
a[i++]=n%10;
n/=10;
}
for(i=0;i<3;i++)
{
temp=i;
for(j=i+1;j<3;j++)
{
if(a[temp]>a[j])
temp=j;
}
min=a[temp];
a[temp]=a[i];
a[i]=min;
max=max*10+a[i];
}
return max;
}
int max1(int n)
{
int a[3];
int temp;
int min;
int i=0;
int j=0;
int max=0;
if(n%111==0)
return 0;
while(n)
{
a[i++]=n%10;
n/=10;
}
for(i=0;i<3;i++)
{
temp=i;
for(j=i+1;j<3;j++)
{
if(a[temp]<a[j])
temp=j;
}
min=a[temp];
a[temp]=a[i];
a[i]=min;
max=max*10+a[i];
}
return max;
}
int main()
{
int n;
int count=0;
scanf("%d",&n);
do{
count++;
printf("%d: %d - %d = %d\n",count,max1(n),min1(n),max1(n)-min1(n));
n=max1(n)-min1(n);
}while(n!=495&&n!=0);
}