Description
For any 4-digit integer except the ones with all the digits being the same, if we sort the digits in non-increasing order first, and then in non-decreasing order, a new number can be obtained by taking the second number from the first one. Repeat in this manner we will soon end up at the number 6174 -- the "black hole" of 4-digit numbers. This number is named Kaprekar Constant.
For example, start from 6767, we'll get:
7766 - 6677 = 1089
9810 - 0189 = 9621
9621 - 1269 = 8352
8532 - 2358 = 6174
7641 - 1467 = 6174
Given any 4-digit number, you are supposed to illustrate the way it gets into the black hole.
Input
Each input file contains one test case which gives a positive integer N in the range (0, 10000).
Output
If all the 4 digits of N are the same, print in one line the equation "N - N = 0000". Else print each step of calculation in a line until 6174 comes out as the difference. All the numbers must be printed as 4-digit numbers.
Sample Input
6767
2222
Sample Output
7766 - 6677 = 1089
9810 - 0189 = 9621
9621 - 1269 = 8352
8532 - 2358 = 6174
2222 - 2222 = 0000
解析:n化为4位数后,n数字降序 — n数字升序,如果结果是0或者是6174,结束。
注意点:输入n可能小于4位数,如果直接数值型计算需要进行补零,不然会死循环一直输出,导致Output Limit Exceed,不过可以用数组来存一下,排个序,相减的数即x=a[3]*1000+a[2]*100+a[1]*10+a[0];//数字降序
y=a[0]*1000+a[1]*100+a[2]*10+a[3];//数字升序
#include <stdio.h>
int a[4];
int main()
{
int n,i,j,t,x,y;
while(~scanf("%d",&n)){
while(1){
for(i=0;i<4;i++) a[i]=n%10,n/=10;//将数字保存到数组
for(i=0;i<3;i++){ //冒泡从小到大排序(就4个数,当然sort没问题👍)
for(j=i+1;j<4;j++){
if(a[i]>a[j]) t=a[i],a[i]=a[j],a[j]=t;
}
}
x=a[3]*1000+a[2]*100+a[1]*10+a[0];//数字降序
y=a[0]*1000+a[1]*100+a[2]*10+a[3];//数字升序
printf("%04d - %04d = %04d\n",x,y,x-y);
n=x-y;//更新n
if(n==0||n==6174) break;//满足,退出即可
}
}
return 0;
}