PAT 甲级 1069 数字黑洞 C++ 题解

题目

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
… …

Input Specification:
Each input file contains one test case which gives a positive integer N in the range (0,10​4​​ ).
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

注意点

1.问题中要求输出的数字始终保持4位,不够则用0填充,因此需要考虑输出规格化,在printf中%04d表示输出4位整数,不够时高位补0

2.由于需要升序降序排列,很容易想到要将原有的数字拆分而后使用用sort函数,这里既可以用字符串来存储,也可以用int数组存储,但总体上int数组更为方便。

3.在转换数值与数组过程中,我们是不能直接返回数组的,具体的解决方式有通过返回指针和传参进行修改两种。而需要注意的是,在传参时数组自身可看作一个指针,因此无需额外的引用。

代码实现

# include<cstdio>
# include<algorithm>
using namespace std;

void to_array(int n,int num[]){
	for(int i=0;i<4;i++){
		num[i] = n%10;
		n/=10;
	}
}

int to_int(int num[]){
    int sum = 0;
    for(int i=0;i<4;i++)
		sum = sum*10+num[i];
	return sum;
}

bool cmp(char a, char b)//降序
{
	return a>b;
}

int main()
{
    int MAX,MIN,num;
    int temp_num[4];
    scanf("%d",&num);
    while(1){
        to_array(num,temp_num);
        sort(temp_num,temp_num+4);//默认升序,获得最小值
		MIN = to_int(temp_num);
		sort(temp_num,temp_num+4, cmp);//降序,获得最大值
		MAX = to_int(temp_num);
		num = MAX - MIN;
		printf("%04d - %04d = %04d",MAX,MIN,num);
		if(num!=6174&&num!=0)
			printf("\n");
        else
            break;
    }
    return 0;
}

版权声明:本文为weixin_44031260原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。