题目描述
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,104).
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
题目大意
给定任一个各位数字不完全相同的 4 位正整数,如果我们先把 4 个数字按非递增排序,再按非递减排序,然后用第 1 个数字减第 2 个数字,将得到一个新的数字。一直重复这样做,我们很快会停在有“数字黑洞”之称的 6174,这个神奇的数字也叫 Kaprekar 常数。需要将该过程给显示出来。
注意点(以下除个人评论外均为葵花宝典摘抄)
- 这种按照一定规律或者一定步骤来进行求解的题目,最好是选择用循环来做,并且将其中的特定步骤用函数来表示,这样会方便很多,特别是需要机械性地解决问题时,要学会这种思路;
- 务必记住数组与数字之间相互转换的步骤,这个答案中的转换步骤十分简洁,务必记住;
- 另外英文题的阅读一定要做点笔记,这样可以避免漏掉某些限制条件以及重要条件,可以尝试讲一些特定名词给记下来,毕竟以后也有可能需要用到。
English | Chinese |
---|---|
digit | 数字 |
equation | 方程 |
constant | 常数 |
illustrate | 说明 |
代码如下:
#include<cstdio>
#include<algorithm>
using namespace std;
bool cmp(int a, int b) //递减排序
{
return a > b;
}
void to_array(int a[], int k) //将数字转换为数组
{
for(int i = 0; i < 4; i++)
{
a[i] = k % 10;
k /= 10;
}
}
int to_num(int a[]) //将数组转换为数字
{
int sum = 0;
for(int i = 0; i < 4; i++)
{
sum = sum * 10 + a[i];
}
return sum;
}
int main()
{
int a[5], max, min, k; //min表示降序后得到的数字,max表示升序得到的数字
scanf("%d", &k);
do
{
to_array(a, k); //将n转换为数组
sort(a, a+4); //对num数组中的元素从小到大排序
min = to_num(a); //获取最小值
sort(a, a+4, cmp); //对num数组中的元素从大到小排序
max = to_num(a); //获得最大值
k = max - min; //得到下一个值
printf("%04d - %04d = %04d\n", max, min, k);
}while(k != 6174 && k != 0); //满足特定条件则退出
return 0;
}
尝试背出下面代码:
void to_array(int a[], int k) //将数字转换为数组
{
for(int i = 0; i < 4; i++)
{
a[i] = k % 10;
k /= 10;
}
}
int to_num(int a[]) //将数组转换为数字
{
int sum = 0;
for(int i = 0; i < 4; i++)
{
sum = sum * 10 + a[i];
}
return sum;
}