【PAT甲级】1069 The Black Hole of Numbers (20 分)

题意:

输入一个四位的正整数N,输出每位数字降序排序后的四位数字减去升序排序后的四位数字等于的四位数字,如果数字全部相同或者结果为6174(黑洞循环数字)则停止。

trick:

这道题一反常态的输入的数字是一个int类型而不是包含前导零往常采用字符串的形式输入,所以在测试点2,3,4如果用字符串输入会超时。。。。。

代码:

#define HAVE_STRUCT_TIMESPEC
#include<bits/stdc++.h>
using namespace std;
int n;
char x[7],y[7];
int main(){
scanf("%d",&n);
x[0]=n/1000+'0';
n%=1000;
x[1]=n/100+'0';
n%=100;
x[2]=n/10+'0';
n%=10;
x[3]=n+'0';
while(1){
if(x[0]==x[1]&&x[1]==x[2]&&x[2]==x[3]){
printf("%s - %s = 0000",x,x);
//cout<<x<<" - "<<x<<" = 0000";
return 0;
}
sort(x,x+4);
y[0]=x[3];
y[1]=x[2];
y[2]=x[1];
y[3]=x[0];
int xx=(x[0]-'0')*1000+(x[1]-'0')*100+(x[2]-'0')*10+x[3]-'0';
int yy=(y[0]-'0')*1000+(y[1]-'0')*100+(y[2]-'0')*10+y[3]-'0';
int zz=yy-xx;
printf("%04d - %04d = %04d",yy,xx,zz);
//cout<<yy<<" - "<<xx<<" = "<<zz;
if(zz==6174)
break;
else
printf("\n");
//cout<<"\n";
x[0]=zz/1000+'0';
zz%=1000;
x[1]=zz/100+'0';
zz%=100;
x[2]=zz/10+'0';
zz%=10;
x[3]=zz+'0';
}
return 0;
}

猜你喜欢

转载自www.cnblogs.com/ldudxy/p/11785050.html
今日推荐