PAT (Basic Level) Practice (中文) 1019 数字黑洞
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include<stdio.h> 2 #include<string.h> 3 #include<algorithm> 4 using namespace std; 5 char n[5]; 6 bool cmp(char a,char b){//降序 7 return a>b; 8 } 9 void read(); 10 int changeint(char a[]); 11 void changechar(int z,char a[]); 12 int main(){ 13 read(); 14 int z=0,x,y; 15 if(strlen(n)<4) return 0; 16 while(z!=6174){ 17 sort(n,n+4,cmp); 18 x = changeint(n); 19 sort(n,n+4); 20 y = changeint(n); 21 z = x - y; 22 printf("%04d - %04d = %04d\n",x,y,z); 23 if(x==y) break; 24 else changechar(z,n); 25 } 26 return 0; 27 } 28 void read(){ 29 int x,len=3; 30 scanf("%d",&x); 31 if(x==0) {n[0]='0';return;} 32 while(x!=0){ 33 n[len--] = x%10+'0'; 34 x = x / 10; 35 } 36 for(int i=len;i>=0;i--) n[i]='0'; 37 } 38 int changeint(char a[]){ 39 int len = strlen(a),value=0; 40 for(int i=0;i<len;i++){ 41 value = value *10 + (a[i]-'0'); 42 } 43 return value; 44 } 45 void changechar(int z,char a[]){ 46 int len=3; 47 char b[10]; 48 while(z!=0){ 49 a[len--] = z % 10+'0'; 50 z /= 10; 51 } 52 for(int i=len;i>=0;i--){ 53 a[i]='0'; 54 } 55 return; 56 57 58 }
总结:如果输入的三位数,要转换成四位数进行。注意永远只能有4位数。