您的位置:首页 > 其它

PAT 1069. The Black Hole of Numbers (20) 【超时14/20】

2014-03-16 10:30 399 查看


1069. The Black Hole of Numbers (20)

时间限制

100 ms

内存限制

32000 kB

代码长度限制

16000 B

判题程序

Standard

作者

CHEN, Yue

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 Specification:

Each input file contains one test case which gives a positive integer N in the range (0, 10000).

Output Specification:

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 1:
6767

Sample Output 1:
7766 - 6677 = 1089
9810 - 0189 = 9621
9621 - 1269 = 8352
8532 - 2358 = 6174

Sample Input 2:
2222

Sample Output 2:
2222 - 2222 = 0000


提交代码

不知道为什么会超时。。14/20

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
char ans[10];
bool cmp(char ch1,char ch2)
{
return ch1>ch2;
}
char* minusNum(char t1[],char t2[])
{
int i,carry=0;
for(i=3;i>=0;i--){
if(t1[i]-'0'-carry<t2[i]-'0'){
ans[i]=t1[i]-carry-t2[i]+10+'0'; //注意计算完后 还要转化成字符!!!
carry=1;
}
else{
ans[i]=t1[i]-carry-t2[i]+'0';
carry=0;
}
}
ans[4]='\0';  //构成字符串~
return ans;
}
int main()
{
//freopen("G:\\in.txt","r",stdin);
int i;
char r[10],a[10],b[10];
while(scanf("%s",r)!=EOF){
memset(a,0,sizeof(a));memset(b,0,sizeof(b));
for(i=1;i<4;i++){
if(r[i]==r[0])
continue;
else
break;
}
if(i==4){
printf("%s - %s = 0000\n",r,r);
continue;
}
do{
sort(r,r+4); //默认升序
strcpy(a,r);
sort(r,r+4,cmp); //降序排列
strcpy(b,r);
strcpy(r,minusNum(b,a));
printf("%s - %s = %s\n",b,a,r);
}while(strcmp(r,"6174")!=0);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: