PAT Basic 1019. 数字黑洞
1. 题目描述:
给定任一个各位数字不完全相同的 4 位正整数,如果我们先把 4 个数字按非递增排序,再按非递减排序,然后用第 1 个数字减第 2 个数字,将得到一个新的数字。一直重复这样做,我们很快会停在有“数字黑洞”之称的 6174
,这个神奇的数字也叫 Kaprekar 常数。
例如,我们从6767
开始,将得到
7766 - 6677 = 1089
9810 - 0189 = 9621
9621 - 1269 = 8352
8532 - 2358 = 6174
7641 - 1467 = 6174
... ...
现给定任意 4 位正整数,请编写程序演示到达黑洞的过程。
2. 输入格式:
输入给出一个 \((0,10^4)\) 区间内的正整数 \(N\)。
3. 输出格式:
如果 \(N\) 的 4 位数字全相等,则在一行内输出 N - N = 0000
;否则将计算的每一步在一行内输出,直到 6174
作为差出现,输出格式见样例。注意每个数字按 4
位数格式输出。
4. 输入样例:
6767
2222
5. 输出样例:
7766 - 6677 = 1089
9810 - 0189 = 9621
9621 - 1269 = 8352
8532 - 2358 = 6174
2222 - 2222 = 0000
6. 性能要求:
Code Size Limit
16 KB
Time Limit
200 ms
Memory Limit
64 MB
思路:
这里涉及到对输入数字的各位进行排序,所以我当时把它当作字符串读入,然后定义了两个子函数用冒泡排序分别计算减数和被减数,最后将结果按照要求输出。
这里输出相关的代码分散到各个函数里了,不是很好的写法。。。另外就是把输入当作整数类型读入更好,在两个子函数里计算各位数字就好了。这里的写法一开始有测试点不通过,是因为输入范围是\([1, 9999]\),也就是说输入可能小于4位数字,所以我这里将integers初始化为"0000"
,并且做了额外的操作。
My Code:
#include <stdio.h>
#include <string.h>
int gotInt1(const char integers[]);
int gotInt2(const char integers[]);
int main(void)
{
char integers[5] = "0000";
int temp1 = 0, temp2 = 0, result = 0;
scanf("%s", integers);
for(int i=0;i<4;i++)
{
if(integers[i]=='\0')
integers[i]='0';
}
do
{
temp1 = gotInt1(integers);
temp2 = gotInt2(integers);
result = temp1 - temp2;
// if(result)
// printf("%d\n", result);
// else
// printf("0000\n");
temp1 = result;
for(int i=3; i>=0; i--)
{
integers[i] = temp1 % 10 + '0';
temp1 /= 10;
}
printf("%s\n", integers);
}while(result != 6174 && result);
return 0;
}
int gotInt1(const char integers[])
{
int res = 0;
char temp[5], change;
char *pt;
strcpy(temp, integers);
pt = temp;
for(int i=0; i<3; i++)
{
for(int j=0; j<3-i; j++)
{
if(temp[j] < temp[j+1])
{
change = temp[j+1];
temp[j+1] = temp[j];
temp[j] = change;
}
}
}
printf("%s - ", temp);
while(*pt)
{
res = res*10 + (*pt-'0');
pt++;
}
return res;
}
int gotInt2(const char integers[])
{
int res = 0;
char temp[5], change;
char *pt;
strcpy(temp, integers);
pt = temp;
for(int i=0; i<3; i++)
{
for(int j=0; j<3-i; j++)
{
if(temp[j] > temp[j+1])
{
change = temp[j+1];
temp[j+1] = temp[j];
temp[j] = change;
}
}
}
printf("%s = ", temp);
while(*pt)
{
res = res*10 + (*pt-'0');
pt++;
}
return res;
}
标签:integers,PAT,数字,temp,int,char,1019,Basic,6174
From: https://www.cnblogs.com/tacticKing/p/17208268.html